react-xlsx 前台读取excel并且转换为json发送到后台处理

上才艺

首先前台要npm一下react-xlsx

用一个标签来承接你的excel文件并且触发一个onChange事件

   <Button className="margin-right">
                <input  type='file' accept='.xlsx, .xls' onChange={onImportExcel} />
   </Button>

它长这个样子

然后当你选择文件点击确认的时候会触发刚才的onchange事件

      

  let data = [];
  const onImportExcel = file => {

    // 获取上传的文件对象
    const { files } = file.target;
// 通过FileReader对象读取文件
    const fileReader = new FileReader();

    fileReader.onload = event => {
      try {
        const { result } = event.target;
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, { type: 'binary' });
       console.log(workbook)
        // 存储获取到的数据
        // 遍历每张工作表进行读取(这里默认只读取第一张表)
        for (const sheet in workbook.Sheets) {
          // esline-disable-next-line
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            console.log(workbook.Sheets)
            //由于表头都是中文的,这里我们找到表头对应的单元格,直接修改为我们想要的
            workbook.Sheets.第1页.A1.w = 'kid'
            workbook.Sheets.第1页.B1.w = 'yearAndmonth'
            workbook.Sheets.第1页.C1.w = 'oid'
            workbook.Sheets.第1页.F1.w = 'normcode'
            workbook.Sheets.第1页.J1.w = 'temp_nouse'
            workbook.Sheets.第1页.K1.w = 'kpival'
            workbook.Sheets.第1页.L1.w = 'score'
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
       
            console.log(data)
            break; // 如果只取第一张表,就取消注释这行
          }
        }
        message.success('上传成功!')
      } catch (e) {
        // 这里可以抛出文件类型错误不正确的相关提示
        message.error('文件类型不正确!');
      }
    };

// 以二进制方式打开文件

    fileReader.readAsBinaryString(files[0]);
  }

   

那个data就是最终转换后的json数据

扫描二维码关注公众号,回复: 12900590 查看本文章

 workbook.Sheets.第1页.A1.w = 'kid'
            workbook.Sheets.第1页.B1.w = 'yearAndmonth'
            workbook.Sheets.第1页.C1.w = 'oid'
            workbook.Sheets.第1页.F1.w = 'normcode'
            workbook.Sheets.第1页.J1.w = 'temp_nouse'
            workbook.Sheets.第1页.K1.w = 'kpival'
            workbook.Sheets.第1页.L1.w = 'score'

这些方法是用来设置表头的  因为我的表头是中文的   我要转换成和后台一致的才行 

然后就可以发送到后台去愉快的玩耍了

点个赞呗

猜你喜欢

转载自blog.csdn.net/wangzhichaogege/article/details/108263853