![](/img/trans.png)
[英]how to read an Excel file (.XLSX/XLS) with no libraries in JS
[英]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-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>
有什么方法可以使用與.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.