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; } }