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

如何在Node.js中流式加载140MB+的Excel文件至内存?

处理大体积Excel文件的流式读取与转换方案

针对150MB级别的Excel文件,以下是两种可行的流式读取+分批处理方案,同时解决空表头的唯一命名问题:

方案一:利用XLSX库的流式读取能力

你之前对XLSX的流式支持认知有误,它内置了StreamingWorkbookReader可以实现逐行读取,完全避免一次性加载整个文件到内存。结合分批处理和空表头处理的示例代码如下:

const XLSX = require('xlsx');
const fs = require('fs');

// 处理空表头,生成唯一标识
function processEmptyHeaders(headers) {
  const usedNames = new Set();
  return headers.map((header, index) => {
    if (header && header.trim() !== '') {
      const trimmed = header.trim();
      let uniqueHeader = trimmed;
      let count = 1;
      // 处理重复表头
      while (usedNames.has(uniqueHeader)) {
        uniqueHeader = `${trimmed}_${count++}`;
      }
      usedNames.add(uniqueHeader);
      return uniqueHeader;
    }
    // 为空表头生成带序号的唯一标识
    let emptyHeader = `___EMPTY_CELL_${String(index + 1).padStart(2, '0')}_`;
    while (usedNames.has(emptyHeader)) {
      emptyHeader = `___EMPTY_CELL_${String(++index).padStart(2, '0')}_`;
    }
    usedNames.add(emptyHeader);
    return emptyHeader;
  });
}

// 分批处理数据的业务函数
async function processBatch(batchData, sheetName) {
  // 替换为你的实际业务逻辑:转JSON、存储、分析等
  console.log(`处理${sheetName}批次数据,共${batchData.length}行`);
  const jsonResult = JSON.stringify(batchData);
  // 后续处理...
}

async function processLargeExcel(filePath) {
  const stream = fs.createReadStream(filePath);
  const reader = new XLSX.streaming.StreamingWorkbookReader(stream);

  reader.on('worksheet', async (worksheet) => {
    let headers = [];
    let batch = [];
    const BATCH_SIZE = 1000; // 每批处理1000行

    worksheet.on('row', (row) => {
      // 第一行作为表头
      if (headers.length === 0) {
        headers = row.values.map(cell => cell?.v ?? '');
        headers = processEmptyHeaders(headers);
        return;
      }

      // 组装行数据
      const rowData = {};
      row.values.forEach((cell, index) => {
        if (index >= headers.length) return;
        rowData[headers[index]] = cell?.v ?? null;
      });
      batch.push(rowData);

      // 达到批次阈值则处理
      if (batch.length >= BATCH_SIZE) {
        processBatch([...batch], worksheet.name);
        batch = [];
      }
    });

    // 处理工作表末尾剩余的不足一批的数据
    worksheet.on('end', async () => {
      if (batch.length > 0) {
        await processBatch(batch, worksheet.name);
      }
      console.log(`${worksheet.name}处理完成`);
    });
  });

  reader.on('end', () => console.log('整个Excel文件处理完成'));
  reader.on('error', (err) => console.error('读取出错:', err));
}

// 调用示例
processLargeExcel('./large-excel-file.xlsx');

方案二:使用ExcelJS的流式读取模式

你之前使用readFile会加载全文件,改用文件流读取并开启worksheets: 'emit'配置,即可实现逐工作表、逐行处理,不会触发内存溢出:

const ExcelJS = require('exceljs');
const fs = require('fs');

// 复用空表头处理函数
function processEmptyHeaders(headers) {
  const usedNames = new Set();
  return headers.map((header, index) => {
    if (header && header.trim() !== '') {
      const trimmed = header.trim();
      let uniqueHeader = trimmed;
      let count = 1;
      while (usedNames.has(uniqueHeader)) {
        uniqueHeader = `${trimmed}_${count++}`;
      }
      usedNames.add(uniqueHeader);
      return uniqueHeader;
    }
    let emptyHeader = `___EMPTY_CELL_${String(index + 1).padStart(2, '0')}_`;
    while (usedNames.has(emptyHeader)) {
      emptyHeader = `___EMPTY_CELL_${String(++index).padStart(2, '0')}_`;
    }
    usedNames.add(emptyHeader);
    return emptyHeader;
  });
}

async function processBatch(batchData, sheetName) {
  console.log(`处理${sheetName}批次数据,共${batchData.length}行`);
  const jsonResult = JSON.stringify(batchData);
  // 业务处理逻辑...
}

async function processLargeExcel(filePath) {
  const workbook = new ExcelJS.Workbook();
  const stream = fs.createReadStream(filePath);

  // 流式读取配置:忽略共享字符串减少内存占用,触发工作表事件而非全加载
  await workbook.xlsx.read(stream, {
    sharedStrings: 'ignore',
    worksheets: 'emit'
  });

  workbook.on('worksheet', async (worksheet) => {
    let headers = [];
    let batch = [];
    const BATCH_SIZE = 1000;
    let isFirstRow = true;

    worksheet.on('row', (row) => {
      if (isFirstRow) {
        headers = row.values.map(cell => cell?.value ?? '');
        headers = processEmptyHeaders(headers);
        isFirstRow = false;
        return;
      }

      const rowData = {};
      row.values.forEach((cell, index) => {
        if (index >= headers.length) return;
        rowData[headers[index]] = cell?.value ?? null;
      });
      batch.push(rowData);

      if (batch.length >= BATCH_SIZE) {
        processBatch([...batch], worksheet.name);
        batch = [];
      }
    });

    worksheet.on('finished', async () => {
      if (batch.length > 0) {
        await processBatch(batch, worksheet.name);
      }
      console.log(`${worksheet.name}处理完成`);
    });
  });

  workbook.on('finished', () => console.log('所有工作表处理完成'));
}

// 调用示例
processLargeExcel('./large-excel-file.xlsx');

核心优势

  • 内存友好:流式逐行读取,不会将150MB文件一次性加载到内存,避免溢出
  • 空表头兼容:自动为空白表头生成唯一标识,保证JSON键名的合法性与唯一性
  • 灵活分批:可根据服务器性能调整BATCH_SIZE参数,平衡处理效率与内存占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:36:31