如何更改文件的名称,同时将数据导出到Excel?
<div id="example" class="k-content">
<button type="button"id="btnExport">Export to csv!</button>
<div id="grid"></div>
</div>
<script>
$("#btnExport").click(function (e) {
var result = "data:application/vnd.ms-excel,";
window.open(result);
e.preventDefault();
});
</script>
当我点击导出按钮我得到的download.xls。 是否可以设置文件名作为data.xls? 任何一个可以解释我在哪里,我需要配置?
这里是演示了导出HTML表到Excel中使用自定义文件名的例子: http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/
不仅为Excel中,另外,对于许多种格式的可以用的。
var element = document.createElement('a');
element.setAttribute('href', 'data:application/vnd.ms-excel,' + encodeURIComponent(htmlTable));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
我有同样的问题,因为新的格式(也许不是所有的浏览器支持) <a download=""></a>
以下为我工作得很好。 这直接使用HTML / JavaScript的不PHP服务器的一部分,因为使用提交表单是大数据表太重。
- 改变
<button>
到<a>
- 没有更多的
window.open()
- 使用基本
<a>
行为(所以,没有更多的e.preventDefault()
但改变href
到data:blabla
并添加download="filename"
:
<div id="example" class="k-content">
<a href="#" id="btnExport" >Export to csv!</a>
<div id="grid"></div>
</div>
<script>
$("#btnExport").click(function (e) {
var result = "data:application/vnd.ms-excel,";
this.href = result;
this.download = "my-custom-filename.xls";
return true;
});
</script>
你不能用客户端JavaScript做到这一点,你需要设置响应头...
。净
Response.AddHeader("Content-Disposition", "inline;filename=filename.xls")
或PHP
$filename = 'somehting.xls';
header('Content-Disposition: attachment; filename="'.$filename.'"');
Response.AddHeader "Content-Disposition", "attachment; filename=C:\YOURFILENAME.xls;"
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + ', ' + encodeURIComponent(tab_text);
//setting the file name
a.download = 'SupervisorReport.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
return (a);