第一步:安裝依賴
npm install xlsx file-saver --save
第二步:在組件中導入
import * as FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
第三步:1、給對應表格添加id 2、methods中寫入方法
一.沒有分頁的表格導出
outputFile() {
var ws1 = XLSX.utils.table_to_book(document.querySelector('#Table1'));//對應要導出的表格id
/* get binary string as output */
var wbOut = XLSX.write(ws1, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
FileSaver.saveAs(
new Blob([wbOut], { type: "application/octet-stream" }),
"demo.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbOut);
}
return wbOut;
}
二.有分頁的表格導出
outputFile() {
//因為此處有分頁,每頁展示10條數據,在方法調用的開始,展示所有數據,導出之后再把條數更改過來
this.page.pageSize = this.tableData.length;
this.$nextTick(function () {
var ws1 = XLSX.utils.table_to_book(document.querySelector('#Table1'));//對應要導出的表格id
/* get binary string as output */
var wbOut = XLSX.write(ws1, {
bookType: "xlsx",
bookSST: true,
type: "array"
});
try {
FileSaver.saveAs(
new Blob([wbOut], { type: "application/octet-stream" }),
"demo.xlsx"
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbOut);
}
this.page.pageSize = 10; //表格還原
return wbOut;
});
}
第四步:給按鈕綁定方法outputFile
