需求:
Vue+element UI el-table下的匯出當前所有資料到一個excel檔案裡。
先按照網上的方法,看看有哪些坑
準備工作:
1、安裝依賴:yarn add xlsx file-saver -S
2、在放置需要匯出功能的元件中引入
import FileSaver from "file-saver";
import XLSX from "xlsx";
複製程式碼
3、HTML中的設定,簡單來說就是給需要匯出的table標籤el-table上加一個id:如outTable,對應下面的exportExcel方法中的 document.querySelector(‘#outTable‘)
   //匯出當前表格
exportCurrent:function(){
var wb = XLSX.utils.table_to_book(document.querySelector('#outTable')) //表格id
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheet.xlsx') //檔名
} catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
return wbout
},
複製程式碼
我們來看一下原始資料


還有我的時間,時分秒呢??
原因是因為數字太長了,需要使用excel的文字格式才能顯示正常
經過各種搜尋,最終解決方法如下:
exportExcel() {
var xlsxParam = { raw: true };//轉換成excel時,使用原始的格式
var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
var wbout = XLSX.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
FileSaver.saveAs(
new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
"sheetjs.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;
},
複製程式碼
再來看我們的資料
