gpt4 book ai didi

Javascript 将 html 表导出到 Excel

转载 作者:行者123 更新时间:2023-12-01 16:40:45 29 4
gpt4 key购买 nike

当用户单击“导出”按钮时,我需要将页面中的 html 表格导出到 Excel。现在,我在堆栈溢出上找到了一个适用于 Firefox 的解决方案。

Export dynamic html table to excel in javascript in firefox browser

现在,它不处理像 ö、ü、ö 这样的特殊字符,这些字符在我们这里使用的语言中很常见,所以我想问是否有人知道如何成功导出它们而不会出现问题?

这是我的代码:

 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"><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 };
window.location.href = uri + base64(format(template, ctx));

}

最佳答案

如果添加:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

在文档的头部它将开始按预期工作:

<script type="text/javascript">
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]--><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 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))
}
})()
</script>

Updated Fiddle Here.

关于Javascript 将 html 表导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17142427/

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