html table标签 如何导出为excel ,举例说明下
时间: 2023-11-09 13:11:52 浏览: 44
你好!感谢您的提问。
要将 HTML 表格标签中的数据导出为 Excel,可以使用 JavaScript 库如 SheetJS 或 Blob.js。
示例代码:
```html
<button onclick="exportToExcel('table')">导出为 Excel</button>
<table id="table">
<thead>
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>男</td>
<td>25</td>
</tr>
<tr>
<td>李四</td>
<td>女</td>
<td>30</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.8/xlsx.full.min.js"></script>
<script>
function exportToExcel(tableId) {
var wb = XLSX.utils.table_to_book(document.getElementById(tableId)); // 将表格转换为 Workbook 对象
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' }); // 将 Workbook 对象转换为二进制数据
saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'table.xlsx'); // 下载 Excel 文件
}
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
return buf;
}
</script>
```
这段代码中,首先定义了一个包含表格和导出按钮的 HTML 页面。然后使用 SheetJS 库将表格转换为 Workbook 对象,再将 Workbook 对象转换为二进制数据,并通过 Blob.js 库下载为 Excel 文件。
希望这个答案能够帮到您!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)