代码
<div>
<table id="out-table">
<tr>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
<td>123</td>
</tr>
<tr>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
<td>456</td>
</tr>
<tr>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
<td>789</td>
</tr>
<tr>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
<td>91011</td>
</tr>
</table>
<button @click="exportExcel">导出Excel</button>
</div>
**注意:**安装依赖file-saver和xlsx,其中xlsx默认的版本容易出错或不成功,我安装的xlsx@0.16.8版本。
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
methods:{
//定义导出Excel表格事件
exportExcel() {
// 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去,
var fix = document.querySelector(".el-table__fixed");
/* 从表生成工作簿对象 */
var wb;
if (fix) {
wb = XLSX.utils.table_to_book(
document.querySelector("#out-table").removeChild(fix)
);
document.querySelector("#out-table").appendChild(fix);
} else {
wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
}
/* 获取二进制字符串作为输出 */
var wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array",
});
try {
FileSaver.saveAs(
//Blob 对象表示一个不可变、原始数据的类文件对象。
//Blob 表示的不一定是JavaScript原生格式的数据。
//File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
//返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
new Blob([wbout], { type: "application/octet-stream" }),
//设置导出文件名称
"sheetjs.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
},
}
}