纯前端使用vue如何导出表格

1、 安装依赖
安装依赖xlsx,file-saver

npm install --save xlsx file-saver
2.在组件中引入
import FileSaver from ‘file-saver’
import XLSX from ‘xlsx’
3.添加下载方法
#out-table为table节点的id

outTab () {
   /* generate workbook object from table */
     let wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
     /* get binary string as output */
     let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
     try {
         FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
     } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
     return wbout
 },

4.注意点
使用el-table的filex属性时,会导致生成2份数据
解决方法:

/* generate workbook object from table /
let fix = document.querySelector(’.el-table__fixed’);
let wb;
if (fix) {
wb = XLSX.utils.table_to_book(document.querySelector("#out-table").removeChild(fix));
document.querySelector("#out-table").appendChild(fix);
} else {
wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
}
/
get binary string as output */
let wbout = XLSX.write(wb, {
bookType: ‘xlsx’,
bookSST: true,
type: ‘array’
});

try {
FileSaver.saveAs(new Blob([wbout], {
type: ‘application/octet-stream’
}), ‘file.xlsx’);
} catch (e) {
if (typeof console !== ‘undefined’) console.log(e, wbout)
}
return wbout;

你可能感兴趣的:(前端)