安装依赖
npm install --save xlsx file-saver
引入
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
导出方法
exportExcel(excelName) {
//excelName --设置导出的excel名称
//report-table --对应的要导出的el-table的ref名称
try {
const $e = this.$refs['report-table'].$el;
// 如果表格加了fixed属性,则导出的文件会生产两份一样的数据,所以可在这里判断一下
let $table = $e.querySelector('.el-table__fixed');
if (!$table) {
$table = $e;
}
// 为了返回单元格原始字符串,设置{ raw: true }
const wb = XLSX.utils.table_to_book($table, { raw: true });
const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
FileSaver.saveAs(
new Blob([wbout], { type: 'application/octet-stream' }),
`${excelName}.xlsx`,
);
} catch (e) {
if (typeof console !== 'undefined') console.error(e);
}
}
https://github.com/SheetJS/js-xlsx
https://github.com/eligrey/FileSaver.js
https://segmentfault.com/a/1190000022936812