react解析excel为数组

import * as XLSX from 'xlsx'; 
import { Button, Upload, message } from 'antd';

// 处理文件上传
   const handleInProducts = (info: any) => {
    const file = info.file;
    if (file.status === 'done') {
      const reader = new FileReader();
      reader.onload = (e) => {
        const binaryData = e.target?.result;
        if (binaryData) {
          // 解析 Excel 文件
          const workbook = XLSX.read(binaryData, { type: 'binary' });
          const sheetName = workbook.SheetNames[0]; // 获取第一个工作表
          const sheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(sheet); // 将工作表转换为 JSON 数组

          // 替换键名
          const formattedData = jsonData.map((item: any) => ({
            expressNumber: item['物流单号'], // 将 "物流单号" 替换为 "expressNumber"
            newPrice: item['运费'], // 将 "运费" 替换为 "newPrice"
          }));

          setData(formattedData);
          dispatch<WarehouseDeliveryAction>({
            type: 'warehouseDelivery/importExpressNumberPrice',
            payload: formattedData,
          });
        }
      };
      reader.readAsBinaryString(file.originFileObj);
    } else if (file.status === 'error') {
      message.error('文件上传失败!');
    }
  };

  // Upload 组件的配置
  const uploadProps = {
    accept: '.xlsx, .xls', // 限制文件类型
    showUploadList: false, // 不显示文件列表
    beforeUpload: (file: File) => {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        message.error('只能上传 Excel 文件!');
      }
      return isExcel;
    },
  };
 <Upload 
    {...uploadProps} 
    oading={!!loading.effects['warehouseDelivery/importExpressNumberPrice']} 
    onChange={handleInProducts}>
    导入物流金额
 </Upload>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值