文件读取 使用 new FileReader()
可读取为array buff,二进制字符串等等
另附分段读取文件参考链接:
https://blog.csdn.net/liwang2016384/article/details/80899237
三方包:
https://github.com/SheetJS/js-xlsx
react示例代码:
import React, { Component } from 'react';
import { Button, Icon, message,Upload } from 'antd';
import * as XLSX from 'xlsx';
import styles from './excel.less';
class Excel extends Component {
constructor(props){
super(props);
this.state={
fileList: [],
}
}
onImportExcel = file => {
// 获取上传的文件对象
debugger
// const { files } = file.target;
const files = file;
// 通过FileReader对象读取文件
const fileReader = new FileReader();
fileReader.onload = event => {
try {
const { result } = event.target;
// 以二进制流方式读取得到整份excel表格对象
const workbook = XLSX.read(result, { type: 'binary' });
// 存储获取到的数据
let data = [];
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for (const sheet in workbook.Sheets) {
// esline-disable-next-line
if (workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 转成 json 数据
data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
// break; // 如果只取第一张表,就取消注释这行
}
}
// 最终获取到并且格式化后的 json 数据
message.success('文件解析成功!')
console.log(data);
} catch (e) {
// 这里可以抛出文件类型错误不正确的相关提示
message.error('文件类型不正确!');
}
};
// 以二进制方式打开文件
// fileReader.readAsBinaryString(files[0]);
fileReader.readAsBinaryString(files);
// fileReader.readAsArrayBuffer(files)
}
render() {
return (
<div style={{ marginTop: 100 }}>
{/* <Button className={styles['upload-wrap']}>
<Icon type='upload' />
<input className={styles['file-uploader']} type='file' accept='.xlsx, .xls' onChange={this.onImportExcel} />
<span className={styles['upload-text']}>上传文件</span>
</Button>
<p className={styles['upload-tip']}>支持 .xlsx、.xls 格式的文件</p> */}
<Upload
onRemove={(file) => {
debugger;
this.setState(({ fileList }) => {
const index = fileList.indexOf(file);
const newFileList = fileList.slice();
newFileList.splice(index, 1);
debugger;
return {
fileList: newFileList,
};
});
}}
beforeUpload={(file) => {
this.onImportExcel(file)
this.setState(({ fileList }) => ({
fileList: [...fileList, file],
}));
return false;
}}
fileList={this.state.fileList}
>
<Button icon="upload" disabled={this.state.fileList.length > 0}>选择文件</Button>
</Upload>
<Button style={{ margin: "5px 5px 5px 5px" }} disabled={!this.state.fileList.length > 0} onClick={this.upload} >上传</Button>
</div >
);
}
}
export default Excel;