You need to enable JavaScript to run this app. React项目加载本地xlsx为ArrayBuffer供exceljs使用的webpack问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React项目加载本地xlsx为ArrayBuffer供exceljs使用的webpack问题求助

React项目exceljs加载本地xlsx模板解决方案

你之前尝试失败的核心原因是:file-loader返回的是文件打包后的路径字符串,raw-loader返回的是UTF-8编码的文本字符串,都不是exceljs要求的二进制ArrayBuffer格式,以下是3种可行方案:

方案1:webpack5+原生asset配置+fetch(无需额外安装loader)

  • 第一步:修改webpack配置,添加xlsx文件处理规则(如果是CRA项目可通过eject/craco修改配置)
module.exports = {
  module: {
    rules: [
      {
        test: /\.xlsx$/,
        type: 'asset/resource',
      }
    ]
  }
}
  • 第二步:业务代码中导入路径后用fetch转ArrayBuffer
import templatePath from './resources/template.xlsx';
import ExcelJS from 'exceljs';

const loadTemplate = async () => {
  const workbook = new ExcelJS.Workbook();
  const res = await fetch(templatePath);
  const templateBuffer = await res.arrayBuffer();
  await workbook.xlsx.load(templateBuffer);
  // 后续处理逻辑
  return workbook;
}

方案2:无需修改webpack配置(推荐CRA用户使用)

直接将xlsx模板文件放到项目public目录下(比如存为public/resources/template.xlsx),业务代码直接请求对应静态路径即可:

import ExcelJS from 'exceljs';

const loadTemplate = async () => {
  const workbook = new ExcelJS.Workbook();
  // 路径对应public下的文件相对路径
  const res = await fetch('/resources/template.xlsx');
  const templateBuffer = await res.arrayBuffer();
  await workbook.xlsx.load(templateBuffer);
  return workbook;
}

方案3:使用arraybuffer-loader直接导入ArrayBuffer

  • 第一步:安装对应loader
    npm install arraybuffer-loader --save-dev
  • 第二步:修改webpack配置,添加对应规则(注意删除之前配置的xlsx相关file/raw-loader规则,避免冲突)
module.exports = {
  module: {
    rules: [
      {
        test: /\.xlsx$/,
        use: 'arraybuffer-loader',
      }
    ]
  }
}
  • 第三步:业务代码直接导入使用
import templateBuffer from './resources/template.xlsx';
import ExcelJS from 'exceljs';

const loadTemplate = async () => {
  const workbook = new ExcelJS.Workbook();
  await workbook.xlsx.load(templateBuffer);
  return workbook;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 23:09:03