1. 首先安装依赖
npm install xlsx --save
2. 在组件中导入 xlsx
import XLSX from 'xlsx';
//导出功能前端(tabledata表单的$el数据, excelName表单名称),传给后端的数据格式一般为[[{},{}],[{},{}],]最里面的数组里不能再出现数组
export function exportExcel(tabledata, excelName){
try {
// 如果表格加了fixed属性,则导出的文件会生产两份一样的数据,所以可在这里判断一下
let $table = null
if (tabledata.querySelector(".el-table__fixed")) {
$table = tabledata.querySelector(".el-table__fixed");
}else{
$table = tabledata.querySelector(".el-table__fixed-right");
}
if (!$table) {
$table = tabledata;
}
// 为了返回单元格原始字符串,设置{ 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);
}
}