You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何遍历对象数组并使用excel4node输出至Excel?

使用excel4node遍历对象数组写入Excel的解决方案

嘿,我来帮你搞定这个问题!你已经搭好了excel4node的基础代码框架,只需要加个循环就能把对象数组里的数据批量写入Excel啦,下面是具体的实现步骤和完整代码:

核心思路

  • 先写好Excel的表头(你已经手动写了一部分,我们直接沿用这个逻辑)
  • 用循环遍历你的对象数组,从第2行开始(因为第1行是表头),把每个对象的属性值对应到表头的列中
  • 根据数据类型选择写入方法,比如字符串用string(),数字可以转成number(),当然统一用string()也能正常显示

完整代码示例

async generateExclReport(req, res) {
  try {
    var xl = require('excel4node');
    // 你的对象数组数据源
    const dataArray = [
      { "FirstName": "John", "LastName": "Parker", "Age": "23", "Cat": "23g", "SOP": "Active" },
      { "FirstName": "Rose", "LastName": "Jackson", "Age": "44", "Cat": "44g", "SOP": "InActive" }
    ];

    var wb = new xl.Workbook();
    // 添加工作表
    var ws = wb.addWorksheet('Report');

    // 写入表头(第1行)
    ws.cell(1, 1).string('FirstName');
    ws.cell(1, 2).string('LastName');
    ws.cell(1, 3).string('Age');
    ws.cell(1, 4).string('Cat');
    ws.cell(1, 5).string('SOP');

    // 遍历数组写入数据,行号从2开始
    dataArray.forEach((item, index) => {
      const rowNum = index + 2; // 表头占了第1行,所以数据从第2行开始计数
      ws.cell(rowNum, 1).string(item.FirstName);
      ws.cell(rowNum, 2).string(item.LastName);
      ws.cell(rowNum, 3).string(item.Age); // 要是想把Age转成数字类型,改成 .number(parseInt(item.Age)) 就行
      ws.cell(rowNum, 4).string(item.Cat);
      ws.cell(rowNum, 5).string(item.SOP);
    });

    // 这里根据你的需求处理输出,比如写入本地文件或者返回给前端
    await wb.write('report.xlsx');
    res.status(200).send('Excel报表生成成功');
  } catch (error) {
    console.error('生成Excel报表出错:', error);
    res.status(500).send('生成Excel报表失败');
  }
}

额外优化小技巧

如果你的对象属性可能会变动,不想每次都手动修改表头和写入逻辑,可以自动从对象的键生成表头和对应列:

// 自动生成表头
const headers = Object.keys(dataArray[0]);
headers.forEach((header, colIndex) => {
  ws.cell(1, colIndex + 1).string(header);
});

// 自动遍历属性写入数据
dataArray.forEach((item, rowIndex) => {
  const rowNum = rowIndex + 2;
  headers.forEach((header, colIndex) => {
    ws.cell(rowNum, colIndex + 1).string(item[header]);
  });
});

这样不管你的对象新增或减少属性,代码都能自动适配,不用手动调整~

内容的提问来源于stack exchange,提问作者VIK6Galado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:41:53