【发布时间】:2018-05-24 20:21:54
【问题描述】:
我有一个将 html 表导出到 excel 文件的代码。但现在我必须在单个 excel 文件的多个选项卡中导出 html 表。这是我的代码供参考。 在这段代码中,我有三个不同的表。一旦我单击“导出到 Excel”。将下载 Excel。现在在 excel 文件中有一个选项卡,但现在我希望 excel 文件应该包含多个选项卡。每个选项卡应包含不同的表记录。
<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>
<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
<br><br>
<p>Table 1</p>
<table id="testTable" border="1">
<thead>
<tr>
<th>Num1</th>
<th>Num2</th>
<th>Num3</th>
<th>Num4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
<p>Table 2</p>
<table id="" border="1">
<thead>
<tr>
<th>Alpha1</th>
<th>Alpha2</th>
<th>Alpha3</th>
<th>Alpha4</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
<td>g</td>
<td>h</td>
</tr>
<tr>
<td>i</td>
<td>j</td>
<td>k</td>
<td>l</td>
</tr>
<tr>
<td>m</td>
<td>n</td>
<td>o</td>
<td>p</td>
</tr>
</tbody>
</table>
<p>Table 3</p>
<table id="" border="1">
<thead>
<tr>
<th>Fruit1</th>
<th>Fruit2</th>
<th>Fruit3</th>
<th>Fruit4</th>
</tr>
</thead>
<tbody>
<tr>
<td>apple</td>
<td>apple</td>
<td>apple</td>
<td>apple</td>
</tr>
<tr>
<td>orange</td>
<td>orange</td>
<td>orange</td>
<td>orange</td>
</tr>
<tr>
<td>mango</td>
<td>mango</td>
<td>mango</td>
<td>mango</td>
</tr>
<tr>
<td>graphs</td>
<td>graphs</td>
<td>graphs</td>
<td>graphs</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
您需要使用 PHPExcel 等可用于创建原生格式文件的众多库之一来创建原生电子表格格式文件,例如 BIFF (xls) 或 OfficeOpenXML (xlsx)
标签: javascript php jquery html ajax