【发布时间】:2023-03-27 11:50:01
【问题描述】:
我正在尝试将 HTML 表格转换为 Excel,我尝试使用 JavaScript 函数将简单表格转换为 Excel,它工作正常。如果我有多个表,我将如何将所有表数据添加到 Excel 文件中。这是我尝试过的。我创建了 2 个表并给出了表索引 testTable 和 testTable1。
如何在单击按钮时将这 2 个表 ID 传递给 JavaScript 函数?现在点击按钮,只有第一个表被导出到 Excel,因为我只传递了'testTable'。我如何能够将多个表例如:testTable、testTable1 导出到 Excel 中?
这是 JavaScript:
<script>
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))
}
})()
</script>
这是 HTML 部分,
<table id="testTable">
<thead>
<tr>
<th>Name</th>
<th>ACP</th>
<th>OEMCP</th>
<th>Unix<br>
NT 3.1</th>
<th>Unix<br>
NT 3.51</th>
<th>Unix<br>
95</th>
</tr>
</thead>
</table>
<table id="testTable1">
<thead>
<tr>
<th>Name</th>
<th>ACP</th>
<th>OEMCP</th>
<th>Windows<br>
NT 3.1</th>
<th>Windows<br>
NT 3.51</th>
<th>Windows<br>
95</th>
</tr>
</thead>
</table>
请告诉我,如何做到这一点?
谢谢
【问题讨论】:
-
你不能使用网络服务来解决这个问题。它也可以在没有回发的情况下工作。
标签: javascript html excel export-to-excel