V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zurmokeeper
V2EX  ›  程序员

Node.js/javascript 快速导出多表头的 excel 文件

  •  
  •   zurmokeeper ·
    zurmokeeper · 2023-06-15 18:57:18 +08:00 · 685 次点击
    这是一个创建于 512 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    image.png

    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);
    
    })()
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2831 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 11:18 · PVG 19:18 · LAX 03:18 · JFK 06:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.