其中xlsx是引用的node-xlsx包,
第一步先整理出标题行,后面再添加数据行
import * as xlsx from 'node-xlsx';
export async function exportToExcelWrapper(
response: Response,
result: any[],
preName = '',
): Promise<void> {
const header = [],
rows = [];
if (result.length > 0) {
const first = result[0];
for (const key in first) {
header.push(key);
}
rows.push(header);
await Promise.all(
result.map(r => {
const row = [];
for (const key in r) {
row.push(r[key]);
}
rows.push(row);
}),
);
}
const buffer = xlsx.build([{ name: 'sheet1', data: rows }]);
let fileName = getStandardDateTimeString() + '.xlsx';
if (preName) {
fileName = preName + '_' + fileName;
}
const downloadOptions = {
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURI(
fileName,
)}`,
'Content-Type':
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
const bufferStream = new Stream.PassThrough();
bufferStream.end(Buffer.from(buffer));
bufferStream.pipe(response).writeHead(200, downloadOptions);
}