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

时间:2018-05-16 08:14:08

标签: javascript excel reactjs csv

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

例如以下文件

enter image description here

会输出:

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>

我是否可以使用与.xls文件相同的方式获取.xlsx.csv文件的内容?或者也许是另一个模块......

1 个答案:

答案 0 :(得分:1)

我将代码添加为以下代码,

选择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();
  }