📅  最后修改于: 2023-12-03 15:31:19.723000             🧑  作者: Mango
有时候,我们需要将网页上的数据导出为Excel文件,以便在其他应用程序中使用。本文将介绍如何使用JavaScript将HTML表格转换为Excel文件。我们将使用以下库:
首先,我们需要在HTML中创建表格,例如:
<table id="my-table">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Smith</td>
<td>Male</td>
<td>35</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>Female</td>
<td>28</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.8/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
function exportTableToExcel(tableId, filename = ''){
const wb = xlsx.utils.table_to_book(document.querySelector(`#${tableId}`), {sheet:"Sheet JS"});
const wbout = xlsx.write(wb, {bookType:'xlsx', type: 'binary', compression:true});
function s2ab(s) {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (let i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
const blob = new Blob([s2ab(wbout)],{type:"application/octet-stream"});
saveAs(blob, `${filename}.xlsx`);
}
document.querySelector('#download').addEventListener('click', () => {
exportTableToExcel('my-table', 'myfilename');
});
function exportTableToExcel(tableId, filename = ''){
const wb = xlsx.utils.table_to_book(document.querySelector(`#${tableId}`), {sheet:"Sheet JS"});
const wbout = xlsx.write(wb, {bookType:'xlsx', type: 'binary', compression:true});
function s2ab(s) {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (let i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
const blob = new Blob([s2ab(wbout)],{type:"application/octet-stream"});
saveAs(blob, `${filename}.xlsx`);
}
document.querySelector('#download').addEventListener('click', () => {
exportTableToExcel('my-table', 'myfilename');
});
以上代码将创建一个名为“下载”的按钮,当单击它时,将默认下载名为“myfilename.xlsx”的Excel文件,其中包含ID为“my-table”的HTML表格中的数据。