gpt4 book ai didi

javascript - Angular2 - 将表导出到 html excel 并给出文件名

转载 作者:行者123 更新时间:2023-12-01 03:30:27 25 4
gpt4 key购买 nike

我有一个Angular2应用程序,现在它要求我实现一个基本表格导出至 Excel

我正在使用的函数可以工作,但我不知道如何设置生成的 Excel 的文件名。

这是函数:

tableToExcel(e,table, name) {
console.log(e);

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(decodeURI(decodeURIComponent(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
}
//window.location.href = uri + base64(format(template, ctx))
console.log(uri + base64(format(template, ctx)));
window.open(uri + base64(format(template, ctx)), '_blank', 'top=0,left=0,height=100%,width=auto');

return false;
}

这是按钮:

<a type="button" href="#" (click)="tableToExcel($event,'testTable', 'W3C Example Table')" download="Schede.xlsx" class="btn btn-warning"> Excel </a>

此时我可以下载 Excel 文件,但文件名完全是随机的

感谢支持

最佳答案

试试这个代码。您可以提供所需的文件名来代替 Test file.xls

tableToExcel(table, name) {
template =
'<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"e
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>
(<HTMLScriptElementdocument.getElementById(table)).innerHTML</table>
</body>
</html>',

if (window.navigator.msSaveBlob) {
var blob = new Blob([templete], {type: "application/csv;charset=utf-8;"});
navigator.msSaveBlob(blob, 'Test file.xls');
}
}

关于javascript - Angular2 - 将表导出到 html excel 并给出文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44567559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com