设置从html表导出的Excel表的文件名
本文关键字:Excel 文件名 html 设置 | 更新日期: 2023-09-27 18:05:29
我有一个html表。现在我将此表导出到Excel工作表使用Javascript。当这个excel表格被下载时文件名类似于"download.xls"。现在我想要文件名为current_date而不是"下载"…下面是我的javascript代码:
function write_to_excel() {
var tab_text = "<table border='2px'><tr>";
var textRange; var j = 0;
tab = document.getElementById('tt1'); // id of table
tab1 = document.getElementById('testTable'); // id of table
for (i = 0; i < tab.rows.length; i++) {
tab_text = tab_text + tab.rows[i].innerHTML + "</tr>";
//tab_text=tab_text+"</tr>";
}
for (j = 0; j < tab1.rows.length; j++) {
tab_text = tab_text + tab1.rows[j].innerHTML + "</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text = tab_text + "</table>";
tab_text = tab_text.replace(/<A[^>]*>|<'/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<'/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv':11'./)) // If Internet Explorer
{
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, "Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
This event is fired on a button click event. Its very important for me.
Thanks in advance.
function tableToExcel (table, name) {
var uri = 'data:application/vnd.ms-excel;base64,'
,
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
}
, format = function (s, c) {
return s.replace(/{('w+)}/g, function (m, p) {
return c[p];
})
}
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
var a = document.createElement('a');
a.href = uri + base64(format(template, ctx))
a.download = name+'.xls';
//triggering the function
a.click();
}
可以看到:如何更改文件的名称,同时导出数据到Excel?
这:http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/