欢迎加入站点基地设计开发交流群:30720409
详细内容
当前位置 首页 >> 技术文档 >> NodeJS >> 正文
nodejs导出excel
发布日期:2022-01-19     点击:226     字体:[ ]

其中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);
}


用户评论
昵称 
内容  *
验证码   
   
Copyright © 2010 zdbase.com All Rights Reserved. 苏ICP备15039389号-1 可人软件设计