前端解析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)
}
相关推荐
花开盛夏^.^7 小时前
电脑打开多个浏览器Web窗口占用较大的运行内存的原因
前端·浏览器
馒头不想说话8 小时前
实体店老板的24小时AI运营员工,写、剪、发全自动,省下一整个团队工资
前端
椒哥10 小时前
一天被问几十次"允许",我统计了 517 次,然后写了个插件
前端·javascript·github
风骏时光牛马10 小时前
生成一个AI稳定性治理及疑难问题分析标题,只需要一个标题,不需要其他的任何文本。
前端
莫西干式秃头10 小时前
用 AI + threejs 写了个浏览器里的 3D 动作游戏《武来》:砍怪、放技能、开 SU7
前端·人工智能·three.js
kyriewen10 小时前
我测了 6 种防请求竞态的写法:只有 1 种真能打
前端·javascript·程序员
孟健10 小时前
用 WorkBuddy 做个人名片网页,挂上开源设计技能后效果完全不同了
前端·人工智能·ai编程
IT_陈寒10 小时前
SpringBoot自动配置的坑,这次终于爬出来了
前端·人工智能·后端
LuHang12 小时前
从天地图切换到高德地图:一次真实的底图迁移实战
前端·vue.js·cesium
用户3600555790012 小时前
Kestrel_VLLM - 27 · 寄存器常驻与融合发射:两次「少发一次」
前端