elementUI的表格沒有提供導出excel的功能接口
通用的方式都是用插件xlsx和file-saver來實作檔案導出,具體代碼如下:
exportExcel () {
//指定想要導出表格的id
let wb = XLSX.utils.table_to_book(document.querySelector('#yourTableId'));
//資料寫入
let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
//表格的參數
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'yourFileName.xlsx')
} catch (e) {
if(typeof console !== 'undefined')
console.log(e, wbout)
}
return wbout;
},
然後我導出的時候excel内容卻重複了,如下:
造成這樣的原因是使用了布局:
fixed:right;
在elementUI裡為了固定右邊的操作欄,實作方式是寫了兩個table,隐藏掉其中一個的左邊部分(具體讀者看看浏覽器的html代碼就知道了),這導緻
XLSX.utils.table_to_book
得到的table有兩個,是以内容就重複了。
解決方法:
- 把fixed布局去掉自然就不會有這個問題
- 先remove掉其中一個表格塊,
得到我們想要的表格内容之後,再把remove的Dom塊append回去,代碼如下:XLSX.utils.table_to_book
exportExcel () {
//這裡的類名可以自己具體看看html代碼
let fix = document.querySelector('.el-table__fixed-right');
let wb;
if (fix) {
//去掉之後,再添加回來
wb = XLSX.utils.table_to_book(document.querySelector('#problemTable').removeChild(fix));
document.querySelector(id).appendChild(fix);
} else {
wb = XLSX.utils.table_to_book(document.querySelector('#problemTable'));
}
//資料寫入
let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
//表格的參數
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '題目.xlsx')
} catch (e) {
if(typeof console !== 'undefined')
console.log(e, wbout)
}
return wbout;
},