如何在将数据导出到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?任何人都能解释我需要配置的地方吗?
答案 0 :(得分:7)
这是一个示例,演示如何使用自定义文件名导出HTML表格:http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/
答案 1 :(得分:5)
不仅适用于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);
答案 2 :(得分:3)
我遇到了同样的问题,而且由于新格式(可能并不是每个浏览器都支持)<a download=""></a>
以下内容对我来说很好。这直接使用没有PHP服务器部分的HTML / Javascript,因为使用提交表单对于大数据表来说太重了。
<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>
答案 3 :(得分:1)
您无法使用客户端JavaScript执行此操作,您需要设置响应标头...
.NET
Response.AddHeader("Content-Disposition", "inline;filename=filename.xls")
或PHP
$filename = 'somehting.xls';
header('Content-Disposition: attachment; filename="'.$filename.'"');
答案 4 :(得分:1)
Response.AddHeader "Content-Disposition", "attachment; filename=C:\YOURFILENAME.xls;"
答案 5 :(得分:0)
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);