前端解析excel

第一步:安装xlsx;

npm install xlsx

第二步:将文件解析成json

2.1使用并获取excel中sheet1、sheet2的对应数据

复制代码
    const workbook = (await excelToJsonAll(e.file)) || [];
    const sheetNameArr = workbook.SheetNames.filter((item) =>
      item.includes('_Schema'),
    );
    let sheet1, sheet2;
    if (sheetNameArr.length > 0) {
      // 解析出来包含_Schema的sheet
      sheet1 = getIndexSheetData(workbook, 1);
      sheet2 = getIndexSheetData(workbook, 2);
    } else {
      sheet1 = getIndexSheetData(workbook, 0);
      sheet2 = getIndexSheetData(workbook, 1);
    }

2.2封装解析方法

复制代码
// 从工作簿中获取第几个工作表的数据
export function getIndexSheetData(
  workbook: WorkBook,
  index: number = 0,
): any[] {
  const firstSheetName = workbook.SheetNames[index];
  if (!firstSheetName) {
    throw new Error('No sheets found in the workbook');
  }

  const workSheet = workbook.Sheets[firstSheetName];
  if (!workSheet) {
    throw new Error(`Sheet "${firstSheetName}" not found in the workbook`);
  }

  return utils.sheet_to_json(workSheet);
}


// 读取 Excel 文件并转换为 JSON 数据
export async function excelToJsonAll(file: File) {
  const buffer = await file.arrayBuffer(); // 读取文件并转换为 ArrayBuffer

  const data = new Uint8Array(buffer);
  const workbook = read(data, { type: 'array' });
  // 对第一个进行校验是否有
  const firstSheetName = workbook.SheetNames[0];
  if (!firstSheetName) {
    throw new Error('No sheets found in the workbook');
  }

  const workSheet = workbook.Sheets[firstSheetName];
  if (!workSheet) {
    throw new Error(`Sheet "${firstSheetName}" not found in the workbook`);
  }

  return workbook;
}

第三步:获取excel的数据

复制代码
let data=[] 
for (const material of sheet1) {
      const value= toString(material['表头文字']);
      ....
      data.push(value)
}
相关推荐
saber_andlibert1 小时前
TCMalloc底层实现
java·前端·网络
逍遥德1 小时前
如何学编程之01.理论篇.如何通过阅读代码来提高自己的编程能力?
前端·后端·程序人生·重构·软件构建·代码规范
冻感糕人~1 小时前
【珍藏必备】ReAct框架实战指南:从零开始构建AI智能体,让大模型学会思考与行动
java·前端·人工智能·react.js·大模型·就业·大模型学习
程序员agions2 小时前
2026年,“配置工程师“终于死绝了
前端·程序人生
alice--小文子2 小时前
cursor-mcp工具使用
java·服务器·前端
晚霞的不甘2 小时前
揭秘 CANN 内存管理:如何让大模型在小设备上“轻装上阵”?
前端·数据库·经验分享·flutter·3d
小迷糊的学习记录2 小时前
0.1 + 0.2 不等于 0.3
前端·javascript·面试
梦帮科技3 小时前
Node.js配置生成器CLI工具开发实战
前端·人工智能·windows·前端框架·node.js·json
VT.馒头3 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
css趣多多3 小时前
一个UI内置组件el-scrollbar
前端·javascript·vue.js