1.安装相关依赖 xlsx file-saver
npm intall --save xlsx
npm intall --save file-saver
2.在组件头里边引入插件
import FileSaver from "file-saver";
import XLSX from "xlsx";
3.定义导出Excel表格事件
exportExcel() { let fix = document.querySelector(".el-table__fixed"); let wb; if (fix) { //判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去 可以避免行重复 wb = XLSX.utils.table_to_book( document.querySelector("#table").removeChild(fix) ); document.querySelector("#table").appendChild(fix); } else { wb = XLSX.utils.table_to_book(document.querySelector("#table")); } let wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array", }); try { //文件名可以自定义 FileSaver.saveAs( new Blob([wbout], { type: "application/octet-stream" }), "仪表数据.xlsx" ); } catch (e) { if (typeof console !== "undefined") console.log(e, wbout); } return wbout; },
4.template中
table加上id
按钮绑定导出excel事件
<el-button type="primary" @click="exportExcel" >导出表格</el-button >
这样就可以了