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

使用XLSX库读取本地xlsx文件报Invalid HTML错误,求解决

解决XLSX读取Excel文件报错"Invalid HTML: could not find "并转为数组

错误原因

你遇到的错误是因为fetch请求返回的不是预期的Excel文件,而是HTML(比如404错误页面)。XLSX库尝试将HTML内容当作Excel解析,就会抛出该错误。核心问题是文件路径配置错误:src目录下的文件在项目打包后不会直接暴露在根路径,直接用./excel/data.xlsx无法正确获取到文件。

解决方案

方案1:将Excel文件移至public目录

把src/excel/data.xlsx移动到项目根目录的public/excel/data.xlsx,public目录下的文件会被直接复制到打包后的根目录,此时可以通过绝对路径访问:

import * as XLSX from "xlsx";

export function App() {
  fetch("/excel/data.xlsx")
    .then((res) => {
      // 先判断请求是否成功
      if (!res.ok) throw new Error("Excel文件加载失败");
      return res.arrayBuffer();
    })
    .then((ab) => {
      // 读取工作簿
      const wb = XLSX.read(ab, { type: "array" });
      // 获取第一个工作表名称
      const firstSheetName = wb.SheetNames[0];
      // 获取工作表内容
      const worksheet = wb.Sheets[firstSheetName];
      // 转换为二维数组(header:1表示用第一行作为数组的子项,若要对象格式可去掉该配置)
      const dataArray = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      console.log("转换后的数组数据:", dataArray);
    })
    .catch((error) => {
      console.error("处理Excel文件出错:", error);
    });

  return <div>Hello World</div>;
}

方案2:通过模块导入文件路径

如果不想移动文件,可直接导入src下的Excel文件,webpack等打包工具会自动处理文件路径:

import * as XLSX from "xlsx";
// 直接导入Excel文件,获取其打包后的访问路径
import excelFilePath from "./excel/data.xlsx";

export function App() {
  fetch(excelFilePath)
    .then((res) => {
      if (!res.ok) throw new Error("Excel文件加载失败");
      return res.arrayBuffer();
    })
    .then((ab) => {
      const wb = XLSX.read(ab, { type: "array" });
      const firstSheetName = wb.SheetNames[0];
      const worksheet = wb.Sheets[firstSheetName];
      const dataArray = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      console.log("转换后的数组数据:", dataArray);
    })
    .catch((error) => {
      console.error("处理Excel文件出错:", error);
    });

  return <div>Hello World</div>;
}

关键说明

  • XLSX.utils.sheet_to_json的header:1配置会将Excel内容转为二维数组;如果需要将每行转为对象(用第一行作为键名),可移除该配置。
  • 一定要添加请求成功的判断(res.ok),避免解析无效内容导致错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:15:32