[英]How to upload and read .csv, .xls and .xlsx in React
I'm trying to upload a file with the format of .csv/.xls/.xlsx
and then read the file contents.我正在尝试上传.csv/.xls/.xlsx
格式的文件,然后读取文件内容。
For example the following file例如下面的文件
would output:会输出:
name,age,key
Mark,25,1
Jones,30,2
This is what I've implemented so far using react-file-reader and base-62 but it only works for the .csv
files:这是我到目前为止使用react-file-reader和base-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>
Is there any way I can get the content of .xls
and .xlsx
files using the same way as I did for .csv
files?有什么方法可以使用与.csv
文件相同的方式获取.xls
和.xlsx
文件的内容吗? Or maybe another module that does this...或者也许另一个模块可以做到这一点......
I added the code as bellow,我添加了以下代码,
Select Excel File选择 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>
then I wrote the handleFiles as following and it was successful for me,然后我写了 handleFiles 如下,它对我来说是成功的,
handleFiles = files => { this.showLoading(); 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.