繁体   English   中英

如何在 React 中上传和读取 .csv、.xls 和 .xlsx

[英]How to upload and read .csv, .xls and .xlsx in React

我正在尝试上传.csv/.xls/.xlsx格式的文件,然后读取文件内容。

例如下面的文件

在此处输入图片说明

会输出:

name,age,key  
Mark,25,1  
Jones,30,2

这是我到目前为止使用react-file-readerbase-62 实现的,但它只适用于.csv文件:

  onFileUpload(file) {
    var decodedData = base64.decode(file.base64);
  }

  <ReactFileReader fileTypes={[".csv",".xls", ".xlsx"]} base64={true} multipleFiles={false} handleFiles={this.onFileUpload}>
    <button className='btn'>Upload</button>
  </ReactFileReader>

有什么方法可以使用与.csv文件相同的方式获取.xls.xlsx文件的内容吗? 或者也许另一个模块可以做到这一点......

我添加了以下代码,

选择 Excel 文件

                        <ReactFileReader handleFiles={this.handleFiles} fileTypes={[".xls", ".xlsx", ".csv"]} base64={true}>
                            <button className='btn btn-warning btn-sm'>Select File</button>
                            { this.state.isFileLoaded ? <label>File Loaded</label> 
                            : <label>File Not Selected</label>  }
                        </ReactFileReader>

                        <span id="errprojectLogoUrl" className="text text-danger"></span>

然后我写了 handleFiles 如下,它对我来说是成功的,

handleFiles = 文件 => { this.showLoading();

    const currentMsgModal = {
        ...this.state.messageModal
    };

    currentMsgModal["isModalHidden"] = true;

    let jsonBase64 = files.base64;
    let index = jsonBase64.indexOf(',');
    let encodedString = jsonBase64.substr(index + 1);
            
    let fileName = files.fileList[0].name;
    let formatString = /[^.]*$/.exec(fileName)[0];

    let isCSVFile = formatString.includes('csv');
    let isXLSFile = formatString.includes('xls');
    let isXLSXFile = formatString.includes('xlsx');
    

    if (isCSVFile || isXLSFile || isXLSXFile)
    {
        this.setState({
            inputFileBaseString: encodedString,
            isFileLoaded: true,
            messageModal: currentMsgModal
        });
    }
    else
    {
        currentMsgModal["messageType"] = "Error"
        currentMsgModal["messageDescription"] = "File Type Not Supported"
        currentMsgModal["isModalHidden"] = false;
        
        this.setState({
            messageModal: currentMsgModal
        });
    }
    this.hideLoading();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM