使用xml模板将表导出到Excel



我可以正确地下载并导出我的html表到excel,但有没有一种方法可以更改xlsx文件名,而不是使用默认的"download.xlsx",只想将下载文件设置为"myTemplate".xlsx.

这里是我目前正在使用的功能:

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))
}
})()

TIA 的任何建议/意见

Nevermind刚刚得到了新的解决方案,并将其用作参考:

https://www.codexworld.com/export-html-table-data-to-excel-using-javascript/

您应该从创建一个标签,然后添加链接到它

const tableExelExport =  ( function () {
let 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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></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 async function (table, name) {
if (!table.nodeType) table = document.getElementById(table)
let ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
let downloadLink = document.createElement("a");
let rp_name = await localStorage.getItem("@report_name")
downloadLink.href = uri + base64(format(template, ctx));
downloadLink.download = rp_name;
downloadLink.click();
// window.location.href = uri + base64(format(template, ctx))
}
})()

最新更新