我正在尝试将多个表格从网页导出到 Excel 工作簿,每个表格一个工作表,有人设法做到这一点而无需将表格转换为 <rows>
并利用 html <table>
xml,即里面<body></body>
.
目前我正在使用以下函数,但虽然它确实创建了多个工作表,但它会将所有表格放入第一个工作表中。
function arrayToExcel(tablesId, filename) {
var uri = 'data:application/vnd.ms-excel;base64,';
var worksheetTemplate = '<x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions><table>{table}</table></x:ExcelWorksheet>';
var format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
var worksheets = tablesId.map(function(name){
return format(worksheetTemplate, {worksheet: name});
}).join('');
var tables = tablesId.map(function(txt){
var table = document.getElementById(txt).innerHTML;
return format(tableTemplate, {table});
}).join('');
var formattedXML = '<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><o:DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><o:Author>Dominik Dumaine</o:Author><o:Created>'+ (new Date()).getTime() +'</o:Created></o:DocumentProperties>'
+'<x:ExcelWorkbook><x:ExcelWorksheets>'
+ worksheets
+'</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body>'
+ tables
+'</body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
window.location.href = uri + base64(formattedXML);
}
像这样使用arrayToExcel(["tbl1","tbl2"], "Name of Workbook")
有没有人对我如何修改上面的内容有任何建议,以便不同的表格转到不同的工作表? 带有附加内联 CSS 的 HTML 看起来像这样:
<table id="tbl1" class="table2excel">
<tr>
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>Butter</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
<hr>
<table id="tbl2" class="table2excel">
<tr>
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>Butter</td>
<td>14</td>
<td>15</td>
<td>16</td>
</tr>
</table>
注意:我看过 Butani Vijay 对 How to convert html table to excel with multiple sheet? 的回答, 不满足我的要求
最佳答案
安装 table2excel(你只需要 JavaScript 文件 table2excel.js):
<head><script src="table2excel.js"></script></head>
那么脚本就是:
const table1 = document.getElementById('table1');
const table2 = document.getElementById('table2');
document.getElementById('downloadexcel').addEventListener('click', function(){
var table2excel = new Table2Excel();
var tables = [table1,table2];
table2excel.export(tables,'multiple_table');
});
如果你想给每个工作表起一个名字,在表格标签内使用data-excel-name。
示例:
<table id="tabel1" data-excel-name="sheet_name_1">
<table id="tabel2" data-excel-name="sheet_name_2">
关于javascript - 将多个 html 表转换为具有多个工作表的 Excel 工作簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47305566/