安装依赖
npm install --save xlsx file-saver
在要用到的文件中引入
<script>
import FileSaver from 'file-saver';
import XLSX from 'xlsx'
</script>
export() {
//不加判断table表格导出会有两份数据,是因为fixed造成的,所以要筛选去重
// 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去
var xlsxParam = { raw: true } // 导出的内容只做解析,不进行格式转换,这样就可以解决时间格式乱码的问题
var fix = document.querySelector('.el-table__fixed');
var exportTable;
if (fix) {
exportTable = XLSX.utils.table_to_book(document.querySelector('#table').removeChild(fix), xlsxParam);
document.querySelector('#table').appendChild(fix);
} else {
exportTable = XLSX.utils.table_to_book(document.querySelector('#table'), xlsxParam);
}
var exportTableOut = XLSX.write(exportTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(
new Blob([exportTableOut], {
type: 'application/octet-stream'
}),
'导出的表格名称.xlsx')
} catch (e) {
if (typeof console !== 'undefined'){
console.log(e, exportTableOut)
}
}
return exportTableOut
},