Requirements: Get the background data, dynamically generate the table, export the excel form, and require the format to be consistent with the table format
Go directly to the code:
<a id="export">导出</a>
<table id="table" class="table table-hover table-bordered" border="1" cellspacing="0">
<thead>
<th>
<td>序号</td>
</th>
<th>
<td>单元</td>
</th>
<th>
<td>措施</td>
</th>
</thead>
<tbody id="TuTable"></tbody>
</table>
The above is the basic part of html. After calling the background interface to obtain data, render the content in tbody, and export the excel form through new Blob():
$("#export").click(()=>{
// 使用outerHTML属性获取整个table元素的HTML代码(包括<table>标签),然后包装成一个完整的HTML文档,设置charset为urf-8以防止中文乱码
var html = "<html><head><meta charset='utf-8' /></head><body>" + document.getElementsByTagName("table")[0].outerHTML + "</body></html>";
// 实例化一个Blob对象,其构造函数的第一个参数是包含文件内容的数组,第二个参数是包含文件类型属性的对象
var blob = new Blob([html], { type: "application/vnd.ms-excel" });
var a = document.getElementsByTagName("a")[0];
// 利用URL.createObjectURL()方法为a元素生成blob URL
a.href = URL.createObjectURL(blob);
// 设置文件名
a.download = "xxx.xls";
})
To learn about Blob, please refer to: Blob - Web API Interface Reference | MDN