1、 安裝相關依賴
npm install --save xlsx file-saver
2、組件裏頭引入
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
3、 導出方法(解決時間問題和兩遍重複數據問題)
exportExcel (id) {
var reportTitle = Date.parse(new Date())+'.xlsx'
/* generate workbook object from table */
// 判斷要導出的節點中是否有fixed的表格,如果有,轉換excel時先將該dom移除,然後append回去,
var fix = document.querySelector('.el-table__fixed-right');
var wb;
var xlsxParam = { raw: true };//轉換成excel時,使用原始的格式
if (fix) {
wb = XLSX.utils.table_to_book(document.querySelector(id).removeChild(fix),xlsxParam);
document.querySelector(id).appendChild(fix);
} else {
wb = XLSX.utils.table_to_book(document.querySelector(id),xlsxParam);
}
/* 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'
}),
reportTitle
);
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout);
}
return wbout;
},