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

如何使用ExcelJS流式WorkbookReader修改现有Excel工作表?

ExcelJS流式处理大文件:修改现有工作表的方案

核心结论

ExcelJS的WorkbookReader是只读流式读取器,本身不支持直接修改原文件的现有工作表;而WorkbookWriter确实只能创建新工作簿/工作表,无法直接编辑原文件内容。要处理大文件的修改需求,需要采用流式读取+流式写入的方式,将修改后的内容输出到新文件中,同时保留原文件的结构。

实现方案示例

以下是基于你的需求修改的完整代码,实现读取原文件、修改指定工作表的内容,并输出到新文件:

const ExcelJS = require("exceljs");

// 读取选项(保持你的配置)
const readerOptions = {
  sharedStrings: "cache",
  hyperlinks: "ignore",
  worksheets: "emit",
  styles: "ignore",
};

async function modifyLargeExcel() {
  // 初始化流式读取器和写入器
  const reader = new ExcelJS.stream.xlsx.WorkbookReader("excel/Book1.xlsx", readerOptions);
  const writer = new ExcelJS.stream.xlsx.WorkbookWriter({
    filename: "excel/Modified_Book1.xlsx",
    useStyles: false, // 匹配读取时的styles: ignore配置
    useSharedStrings: true // 优化内存使用
  });

  // 遍历每个工作表
  for await (const sheet of reader) {
    // 在写入器中创建同名工作表
    const newSheet = writer.addWorksheet(sheet.name);

    // 仅处理名为"FieldDef"的工作表
    if (sheet.name === "FieldDef") {
      // 遍历该工作表的每一行
      for await (const row of sheet) {
        // 修改指定单元格的值
        if (row.getCell(1).value === 21160) {
          row.getCell(1).value = 21161;
        }
        // 将修改后的行写入新工作表
        await newSheet.addRow(row.values).commit();
      }
    } else {
      // 其他工作表直接复制内容(无需修改)
      for await (const row of sheet) {
        await newSheet.addRow(row.values).commit();
      }
    }

    // 提交当前工作表的写入
    await newSheet.commit();
  }

  // 完成整个工作簿的写入
  await writer.commit();
  console.log("文件修改完成,已保存为Modified_Book1.xlsx");
}

modifyLargeExcel().catch(err => console.error("处理出错:", err));

关键说明

  • 流式操作的核心是逐行处理,不会将整个文件加载到内存,适合大文件场景
  • 必须将修改后的内容写入新文件,不能直接修改原文件
  • 调用row.commit()和sheet.commit()是流式写入的必要步骤,确保内容被写入磁盘
  • 如果需要保留原文件的样式、公式等,可以调整读取和写入的配置(比如将styles: "ignore"改为styles: "cache",写入时useStyles: true),但会增加内存消耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:54:24