【基础向】react ant 前端上传excel文件

98 阅读1分钟
需要引入的组件
import * as XLSX from 'xlsx'
import { Button, message, Upload } from 'antd';

  代码 
<Upload
    name='file'
    showUploadList={false}
    accept='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel' 
    beforeUpload={(file) => { imFilt(file) }}
    >
        <MyButton
            onOk={() => { }}
            style={{ backgroundColor: '#008002', color: '#fff', marginLeft: '20px' }}
            text='导入Excel'
        />
 </Upload>
 
 
// 导入数据
    const imFilt = async (file) => {
        const f = file;
        const reader = new FileReader();
        reader.onload = (e) => {
            const datas = e.target.result;
            const workbook = XLSX.read(datas, {
                type: 'binary'
            });
            const first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
            const jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });
            handleImpotedJson(jsonArr, file);
        };
        reader.readAsBinaryString(f);
        return false;
    }
    const handleImpotedJson = (jsonArr, file) => {
        jsonArr.splice(0, 1); // 去掉表头
        const jsonArrData = jsonArr.map((item, index) => {
            let arr = []
            item.forEach((im, i) => {
                let jsonObj = {};
                jsonObj.deviceId = im[0]
                jsonObj.deviceName = im[1]
                jsonObj.deviceType = im[2]
                jsonObj.iccid = im[3]
                jsonObj.remark = im[4]
                jsonObj.operator = im[5]
                jsonObj.deviceType = im[6]
                arr.push(jsonObj)
            })
            return arr;
        });
        console.log(jsonArrData)
    }