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

Next.js中用ExcelJs在浏览器读本地xlsx文件报错:Cannot read properties of undefined (reading 'F_OK')

问题原因

ExcelJS的readFile()是Node.js环境专用的API,它依赖Node内置的fs模块访问本地文件系统。浏览器环境没有fs模块,且出于安全限制不允许直接读取本地文件路径,所以会抛出Cannot read properties of undefined (reading 'F_OK')错误——F_OK是fs.constants中的常量,浏览器中不存在这个对象。

浏览器端解决方案

浏览器要读取本地Excel文件,必须通过用户主动上传获取文件对象,再用ExcelJS的load()方法加载文件二进制数据。

实现步骤

  • 添加文件上传的HTML元素,让用户选择本地Excel文件
  • 监听文件选择事件,读取文件的ArrayBuffer
  • 用workbook.xlsx.load()加载buffer,提取指定列数据

完整代码示例

<!-- HTML部分 -->
<input type="file" id="excelFileInput" accept=".xlsx">

<script src="https://cdn.jsdelivr.net/npm/exceljs@4.3.0/dist/exceljs.min.js"></script>
<script>
async function readExcel(file) {
  const workbook = new Excel.Workbook();
  
  try {
    // 读取文件的ArrayBuffer
    const arrayBuffer = await file.arrayBuffer();
    // 加载二进制数据到workbook
    await workbook.xlsx.load(arrayBuffer);
    
    const sheet = workbook.getWorksheet('Sheet1');
    if (!sheet) {
      console.error('找不到Sheet1工作表');
      return;
    }

    // 提取第1列从第2行开始的数据(可根据需求调整行号和列号)
    const targetColumnData = [];
    sheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
      if (rowNumber >= 2) {
        const cellValue = row.getCell(1).value;
        if (cellValue) {
          targetColumnData.push(cellValue);
        }
      }
    });

    console.log('指定列数据:', targetColumnData);
    return targetColumnData;
  } catch (error) {
    console.error('读取Excel失败:', error);
    throw error;
  }
}

// 监听文件选择事件
document.getElementById('excelFileInput').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  if (!file) return;
  
  // 校验文件格式
  if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    alert('请选择.xlsx格式的Excel文件');
    return;
  }

  await readExcel(file);
});
</script>

关键说明

  • 浏览器无法直接通过文件路径读取本地文件,必须通过用户交互获取File对象
  • 用load()替代readFile(),传入文件的ArrayBuffer数据
  • 代码中默认提取第1列、从第2行开始的数据,可根据需求修改行号(rowNumber >= 2)和列号(getCell(1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:31:43