后台管理系统经常有表格文件导出为excl的需求,在这里记录一下.
这里用到了两个包(file-server,XLSX), 今天项目中遇到这个需求了,但是用这个导出的时候出了问题,在安装的时候没有指定包版本,安装了最新版本,导致XLSX引入报undefined的问题,可能是新版本不兼容的问题
安装
npm install xlsx@0.16.0 file-saver@2.0.2 --save
封装
import FileSaver from "file-saver";
import xlxs from "xlsx";
// 导出excel
const state = reactive({
excelTitle: "用户数据",
});
export const getExcel = () => {
// 设置当前日期
let time = new Date();
let year = time.getFullYear();
let month = time.getMonth() + 1;
let day = time.getDate();
let name = year + "" + month + "" + day;
// 导出文件名
const filename = state.excelTitle;
// 通过id,获取导出的表格数据
const wb = xlxs.utils.table_to_book(document.getElementById("table"), {
raw: true,
});
const wbout = xlxs.write(wb, {
bookType: "xlsx",
bookSST: true,
type: "array",
});
try {
FileSaver.saveAs(
new Blob([wbout], {
type: "application/octet-stream",
}),
name + ".xlsx"
);
} catch (e) {
console.log(e);
}
return wbout;
}
原创文章,作者:jamestackk,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/267327.html