vue3.0 将接口 json 数据导出为.xlsx 文件
注意: 导出的数据应与页面的显示的一致
1.前置数据和配置
const columns = [
{
title: "计划名称",
dataIndex: "planName",
key: "planName",
width: "150px",
},
{
title: "计划开始时间",
dataIndex: "planStartDate",
key: "planStartDate",
customRender: ({ text }) =>
text ? moment(text).format(DateFormatEnum.YMD) : "--",
},
];
{
"data": [
{ "planName": "计划1", "planStartDate": "2021-06-22 17:27:36" },
{ "planName": "计划2", "planStartDate": "2021-06-22 17:27:54" }
]
}
2. 实现
export function json2xlsx(props) {
const { columns, list, filename = "data" } = props;
const map = {};
columns.forEach((o) => {
map[o.key] = {
title: o.title,
customRender: o.customRender,
width: Number.parseFloat(o.width) || 120,
};
});
const cellWidth = [];
const data = list.map((o: T) => {
const item = {};
Object.keys(o).forEach((k) => {
if (map[k]) {
item[map[k].title] = map[k].customRender
? map[k].customRender({ text: o[k] })
: o[k];
cellWidth.push({ wpx: map[k].width });
}
});
return item;
});
const ws = XLSX.utils.json_to_sheet(data);
ws["!cols"] = cellWidth;
ws["!rows"] = [{ hpx: 30 }];
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "sheet");
XLSX.writeFile(wb, `${filename}.xlsx`);
}