1.定义列名
const column = [
{
title: 'xx',
key: 'xx',
},
{
title: 'xx2',
key: 'xx22',
},
{
title: 'xx3',
key: 'xx33',
},
]
2.加工列
const generateColumns = (length: number, props?: any) =>
Array.from({ length }).map((_, columnIndex) => ({
...props,
key: `${columnIndex}`,
dataKey: `${column[columnIndex].key}`,
title: `${column[columnIndex].title}`,
width: 150,
}));
3.导出
function exportExcel() {
const columns = generateColumns(column.length);
const res: string[][] = sourceTableArr.map((it) => {
const arr: any = [];
columns.forEach((column) => {
arr.push(it[column.dataKey]);
});
return arr;
});
const titleList: string[] = [];
columns.forEach((column) => {
titleList.push(column.title);
});
res.unshift(titleList);
const workSheet = XLSX.utils.aoa_to_sheet(res);
const workBook = XLSX.utils.book_new();
workSheet['!cols'] = [
{ wch: 20 },
{ wch: 30 },
{ wch: 30 },
];
XLSX.utils.book_append_sheet(workBook, workSheet, 'xxx信息');
XLSX.writeFile(workBook, '导出表名xxx.xlsx');
}