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