簡體   English   中英

Javascript 將多個 html 表導出到一個 excel 文件

[英]Javascript export multiple html tables to an excel file

我有一個包含多個表的 html 頁面,我想將這些表導出到單個工作表中的單個 excel 文件。 我怎樣才能做到這一點。 我嘗試了以下代碼,它適用於 1 個表。 如何修改代碼導出多張表?

 var tableToExcel = () => { 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)) } }
 <table id="testTable"> <tr> <td>a</td> <td>aaa</td> <td>aaaaaa</td> </tr> <tr> <td>b</td> <td>bbb</td> <td>bbbbbb</td> </tr> </table> <table id="testTable2"> <tr> <td>222a</td> <td>222aaa</td> <td>222aaaaaa</td> </tr> <tr> <td>222b</td> <td>22bbb</td> <td>222bbbbbb</td> </tr> </table> <button onclick="tableToExcel('testTable', 'W3C Example Table')">Export</button>

您可以使用 ExcellentExport.js 庫。 它有助於在客戶端(瀏覽器)創建 XLS、XLSX 或 CSV 文件,從 HTML 表或 JavaScript 數組獲取數據。

https://github.com/jmaister/excellentexport/

示例代碼:

<script>
function export() {
    return ExcellentExport.convert({ anchor: this, filename: 'data_123.array', format: 'xlsx'}, [
        {name: 'Sheet Name Here 1', from: {table: 'testTable'}},
        {name: 'Sheet Name Here 2', from: {table: 'testTable2'}}
    ]);
}
</script>
<a download="somedata.xlsx" href="#" onclick="return export();">Export to XLSX</a>

數組參數包含工作表列表。 第一個元素引用testTable ,第二個元素引用testTable2

注意:我是 ExcellentExport.js 的開發者

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM