首页 > Web开发 > 详细

前端上传excel解析成table 基于react,antd

时间:2021-03-18 11:31:33      阅读:52      评论:0      收藏:0      [点我收藏+]
import React from "react";
import ReactDOM from ‘react-dom‘
import * as XLSX from ‘xlsx‘;
import {Button, message, Table,Upload} from ‘antd‘;
import ExportJsonExcel from ‘js-export-excel‘;
import ‘antd/dist/antd.css‘;
const Dragger = Upload.Dragger;
class Index extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],//表格内容
            columns: [],//表格头部
            data:[]//excel数据
        };
    }
    uploadFilesChange(file) {
        // 通过FileReader对象读取文件
        const fileReader = new FileReader();
        fileReader.readAsBinaryString(file.file);
        fileReader.onload = event => {
            try {
                const { result } = event.target;
                // 以二进制流方式读取得到整份excel表格对象
                const workbook = XLSX.read(result, { type: ‘binary‘ });
                console.log(workbook)
                // 存储获取到的数据
                let data = {
                    
                };
                // 遍历每张工作表进行读取(这里默认只读取第一张表)
                for (const sheet in workbook.Sheets) {
                    let tempData = [];
                    // esline-disable-next-line

                    // console.log(workbook.Sheets[sheet])
                    if (workbook.Sheets.hasOwnProperty(sheet)) {
                        console.log(sheet)
                        // 利用 sheet_to_json 方法将 excel 转成 json 数据
                        data[sheet] = tempData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    }
                }
                console.log(data)
                //上传成功啦,data为上传后的数据
                this.setState({
                    data:data.Sheet1
                });
                // 最终获取到并且格式化后的 json 数据
                message.success(‘上传成功!‘)
                
            } catch (e) {
                // 这里可以抛出文件类型错误不正确的相关提示
                message.error(‘文件类型不正确!‘);
            }
            
            let columns = [];
            let dataSource = [];
            let keys = Object.keys(this.state.data[0]);
            columns = keys.map((item,index)=>{
                return {
                    title:item,
                    dataIndex:item,
                    key:item
                }
            });
           
            dataSource = this.state.data.map((item,index)=>{
                    return {
                        key:index.toString(),
                        "规则协议":item["规则协议"],
                        "端口":item["端口"],
                        "来源":item["来源"],
                        "策略":item["策略"],
                        "备注":item["备注"],
                        "修改时间":item["修改时间"]
                    }
    
            })
            this.setState({
                columns,
                dataSource,
            })
        };
        // 以二进制方式打开文件
    }
    render() {
        const {columns,dataSource} = this.state
        return (
            <div>
                <Dragger name="file"
                         beforeUpload={function () {
                             return false;
                         }}
                         onChange={this.uploadFilesChange.bind(this)}
                         showUploadList={false}>
                    <p className="ant-upload-text">
                        <span>点击上传文件</span>
                        或者拖拽上传
                    </p>
                </Dragger>
                123131
                <Button type="primary" onClick={this.downloadFileToExcel} style={{ marginBottom: "15px" }}>下载</Button>
                <Table columns={columns} dataSource={dataSource}/>
            </div>
        );
    }
}
ReactDOM.render(<Index/>,document.getElementById(‘root‘))
 
antd版本4,解释下sheet是
技术分享图片

 

2021/3/17新建excel默认是会给你建立3个表,我们在用workbook.Sheets,来循环的时候会发现里面其实有三个的原因,excel默认会帮我们创建三个sheet

前端上传excel解析成table 基于react,antd

原文:https://www.cnblogs.com/MDGE/p/14554053.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!