我有代码可以下载像 excel 这样的 HTML 表格
这是代码
var tableToExcel = (function() {
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"><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];
})
}
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table);
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
}
window.location.href = uri + base64(format(template, ctx));
}
})()
<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Експортувати в Excel">
现在它正在下载像“download.xls”,我需要用DateTime 来命名它。我该怎么做?
最佳答案
你应该使用 <a>
带有 download
的元素属性来确定文件的名称。
这是一个如何动态创建 <a>
的示例元素和集合 src
和 download
要下载的属性:
var tableToExcel = (function() {
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"><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];
})
}
return function(table, name) {
// if (!table.nodeType) table = document.getElementById(table);
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
}
// here's how to download with datetime file name.
// DateTime filename
var filename = new Date().getTime();
var element = document.createElement('a');
element.setAttribute('href', uri + base64(format(template, ctx)));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
})()
var table = document.getElementsByTagName('table')[0];
var newTableToExcel = new tableToExcel(table, 'myname');
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
关于javascript - 现在用日期时间命名文件(JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51627085/