Node.js 如何快速导出多表头的excel文件

Node.js 如何快速导出嵌套列(多表头)的excel文件。效果图如下:

Node.js 如何快速导出多表头的excel文件_第1张图片

1:使用 @zurmokeeper/exceljs, V4.4.1以上 安装:

npm i @zurmokeeper/exceljs

2: 有一个 worksheet.makeColumns 方法,API文档: 代码示例:

const ExcelJS = require('@zurmokeeper/exceljs');
(async ()=>{
  const test = 'test.xlsx';

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet1', {
      views: [{state: 'frozen', xSplit: 0, ySplit: 2}], // 冻结第1行和第二行
    });
    // 设置多级表头
    worksheet.makeColumns([
      {
        id: 1,
        title: '姓名',
      },
      {id: 2, title: 'Qwe'},
      {id: 3, title: 'Foo'},
      {
        id: 4,
        title: '基础信息',
        children: [
          {id: 41, title: 'Zoo 1'},
          {id: 42, title: 'Zoo 2'},
          {id: 44, title: 'Zoo 3'},
        ],
      },
      {
        id: 5,
        title: 'Zoo1',
        children: [
          {id: 51, title: 'Zoo 51'},
          {id: 52, title: 'Zoo 52'},
          {id: 54, title: 'Zoo 53'},
        ],
      },
      {id: 6, title: 'Foo123213'},
    ]);
    const data = [
      [1, 2, 3, null, null, 'DOB'],
      [1, 'electron', 'DOB'],
      [1, 'electron', 'DOB'],
      [1, 'electron', 'DOB'],
      [1, 'electron', 'DOB'],
      [1, 'electron', 'DOB'],
      [1, 'electron', 'DOB'],
      [1, 'electron', 'DOB'],
    ];
    worksheet.addRows(data);
    worksheet.columns.forEach(function(column) {
      column.alignment = {horizontal: 'center', vertical: 'middle'};
    });
    await workbook.xlsx.writeFile(test);

})()

你可能感兴趣的:(Node.js 如何快速导出多表头的excel文件)