【发布时间】:2018-04-28 13:39:54
【问题描述】:
我正在尝试将多个表格从网页导出到 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? 的回答,它不符合我的要求
【问题讨论】:
标签: javascript html xml excel html-table