前端实现下载表格数据
程序员文章站
2024-03-20 16:35:16
...
1.html部分table id为“grid-log”,导出按钮id为“exportbtn”,表格数据为bootgrid插件渲染而成
<table id="grid-log" class="table table-condensed table-hover table-striped table-responsive" data-store-selection="true">
<thead>
<tr>
<th data-column-id="pos" data-type="numeric" data-identifier="true" data-visible="false">#</th>
<th data-column-id="timestamp" data-type="string">{{ lang._('Date') }}</th>
<th data-column-id="line" data-type="string">{{ lang._('Line') }}</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<td></td>
<td>
<button id="exportbtn"
data-toggle="tooltip" title="" type="button"
class="btn btn-xs btn-default pull-right"
data-original-title="{{ lang._('download selection')}}">
<span class="fa fa-cloud-download"></span>
</button>
</td>
</tfoot>
</table>
2.前端导出表格数据的重点在于下面几行代码:
// ie10 var blob = new Blob( [ output_data ], { type: "text/csv" } ); navigator.msSaveOrOpenBlob( blob, '{{scope}}.log' );
// Firefox、google
$('<a></a>').attr('id','downloadFile') .attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(output_data)) .attr('download','{{scope}}.log') .appendTo('body');
$('#downloadFile').get(0).click();
// download visible items
$("#exportbtn").click(function(event){
let records = [];
$("#grid-log > tbody > tr").each(function(){
let fields = [];
$(this).find("td").each(function(){fields.push($(this).text().trim())});
records.push(fields.join("\t"));
});
let output_data = records.join("\n");
if($("#downloadFile").length > 0)
$("#downloadFile").remove();
$('<a></a>').attr('id','downloadFile')
.attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(output_data))
.attr('download','{{scope}}.log')
.appendTo('body');
$('#downloadFile').ready(function() {
if ( window.navigator.msSaveOrOpenBlob && window.Blob ) {
var blob = new Blob( [ output_data ], { type: "text/csv" } );
navigator.msSaveOrOpenBlob( blob, '{{scope}}.log' );
} else {
$('#downloadFile').get(0).click();
}
});
});
3.防止用户点击分页按钮后,火狐、谷歌浏览器下载数据不能更新,需清除上次的下载标签,不然不会再次渲染,代码如下:
if($("#downloadFile").length > 0) $("#downloadFile").remove();
上一篇: 前后端分离文件上传
推荐阅读