1、安装xlsx和filesaverjavascript
npm install --save xlsx file-saverhtml
2、在表格组件中引入安装的2个文件java
import FileSaver from "file-saver";npm
import XLSX from "xlsx";app
3、HTML结构spa
<el-table :data="tableData3" style="width: 500px" height="250" id="table"> <el-table-column fixed prop="date" label="日期" width="150"></el-table-column> <el-table-column prop="name" label="姓名" width="120"></el-table-column> <el-table-column prop="province" label="省份" width="120"></el-table-column> <el-table-column prop="city" label="市区" width="120"></el-table-column> <el-table-column prop="address" label="地址" width="300"></el-table-column> <el-table-column prop="zip" label="邮编" width="120"></el-table-column> </el-table> <el-button type="success" style="margin-top:20px;" @click="exportExcel">导出</el-button>
4、导出的方法excel
methods: { exportExcel() { // out-table 关联导出的DOM节点 var fixed = document.querySelector(".el-table__fixed"); var excelTitle = "标题"; var wb = XLSX.utils.table_to_book(document.querySelector("#table")); /* get binary string as output */ var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array" }); try { FileSaver.saveAs( new Blob([wbout], { type: "application/octet-stream" }), excelTitle + ".xlsx" ); } catch (e) { if (typeof console !== "undefined") console.log(e, wbout); } return wbout; } }
在页面点击导出按钮时能够正常导出,可是若是左边有固定的列,相同的数据会导出2遍,能够作以下修改:code
methods: { exportExcel() { // table 关联导出的DOM节点 var fixed = document.querySelector(".el-table__fixed"); var wb; var excelTitle = "标题"; if (fixed) { wb = XLSX.utils.table_to_book( document.querySelector("#table").removeChild(fixed) ); document.querySelector("#table").appendChild(fixed); } else { wb = XLSX.utils.table_to_book(document.querySelector("#table")); } /* get binary string as output */ var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array" }); try { FileSaver.saveAs( new Blob([wbout], { type: "application/octet-stream" }), excelTitle + ".xlsx" ); } catch (e) { if (typeof console !== "undefined") console.log(e, wbout); } return wbout; } }