Export html format table as excel table file
- Download the auxiliary module first.
- Import the auxiliary module to the target html page
- Use DOM operations to get the content of the target table.
- Use the function of the auxiliary module to save the content as a table file.
1. Download auxiliary modules
Here I am using fileSaver, the address is:
https://github.com/kebingzao/fileSaver_excel
Download js (Blob, FileSaver) files, and put them into your project directory:
2. Import the auxiliary module to the target html page
3. Use DOM operations to obtain table content
// 获取表格对象, 并保存为blob
var blob = new Blob([document.getElementById('demo').outerHTML], {
// 指定编码类型, 防止乱码
type: "text/plain;charset=utf-8"
});
4. Use the auxiliary module function to save the content as a table file.
// 使用FileSaver的saveAs方法保存.
saveAs(blob, "export.xls");
to sum up:
Complete code: The
page looks like this (the table object is obtained according to the id):
<table id="demo">
<thead class="top">
<td>名字</td>
<td>性别</td>
<td>年龄</td>
</thead>
<tr>
<td>james</td>
<td>男</td>
<td>35</td>
</tr>
<tr>
<td>kobe</td>
<td>男</td>
<td>42</td>
</tr>
<tr>
<td>wade</td>
<td>男</td>
<td>35</td>
</tr>
</table>
js code:
<script>
// 这里写的是点击函数, 方法为下面的
$('.btn').on('click', () => {
saveAsTable()
})
function saveAsTable() {
// 获取表格对象
var blob = new Blob([document.getElementById('demo').outerHTML], {
type: "text/plain;charset=utf-8"
});
// 使用FileSaver的saveAs方法保存.
saveAs(blob, "mangoo.xls");
}
</script>
Final result:
mangoo.xls