React解析excel文件
首先安装安装xlsx插件
yarn add xlsx
使用xlsx解析
? ? /**
? ? ?* 上传文件并解析成json
? ? ?*/
? ? const HandleImportFile = (info) => {
? ? ? ? let files = info.file;
? ? ? ? // 获取文件名称
? ? ? ? let name = files.name
? ? ? ? // 获取文件后缀
? ? ? ? let suffix = name.substr(name.lastIndexOf("."));
? ? ? ? let reader = new FileReader();
? ? ? ? reader.onload = (event) => {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? // 判断文件类型是否正确
? ? ? ? ? ? ? ? if (".xls" != suffix && ".xlsx" != suffix) {
? ? ? ? ? ? ? ? ? ? message.error("选择Excel格式的文件导入!");
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? let { result } = event.target;
? ? ? ? ? ? ? ? // 读取文件
? ? ? ? ? ? ? ? let workbook = XLSX.read(result, { type: 'binary' });
? ? ? ? ? ? ? ? let data = [];
? ? ? ? ? ? ? ? // 循环文件中的每个表
? ? ? ? ? ? ? ? for (let sheet in workbook.Sheets) {
? ? ? ? ? ? ? ? ? ? if (workbook.Sheets.hasOwnProperty(sheet)) {
? ? ? ? ? ? ? ? ? ? ? ? // 将获取到表中的数据转化为json格式
? ? ? ? ? ? ? ? ? ? ? ? data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? console.log('data:', data);
? ? ? ? ? ? } catch (e) {
? ? ? ? ? ? ? ? message.error('文件类型不正确!');
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? reader.readAsBinaryString(files);
? ? ? ? setIsLoading(false);
? ? }
使用antd的Upload组件上传文件
?<Upload
? ? accept=".xls , .xlsx"
? ? maxCount={1}
? ? showUploadList={false}
? ? customRequest={HandleImportFile}
? >
? ?<Button icon={<UploadOutlined />} type="primary">上传文件</Button>
?</Upload>
React上传excel预览
import React from 'react';
import * as XLSX from 'xlsx';
import {message, Table, Upload} from 'antd';
const { Dragger } = Upload;
export class UploadFile extends React.Component {
state = {
tableData: [],
tableHeader: []
};
toReturn = () => {
this.props.close();
};
toSubmit = () => {
const _this = this;
console.log(_this.state.tableData);
};
render() {
return (
<div>
<Dragger name="file"
accept=".xls,.xlsx" maxCount={1}
beforeUpload={function () {
return false;
}}
onChange={this.uploadFilesChange.bind(this)}
showUploadList={false}>
<p className="ant-upload-text">
<span>点击上传文件</span>
或者拖拽上传
</p>
</Dragger>
<Table
columns={this.state.tableHeader}
dataSource={this.state.tableData}
style={{marginTop: '20px'}}
pagination={false}
/>
</div>
);
}
uploadFilesChange(file) {
// 通过FileReader对象读取文件
const fileReader = new FileReader();
// 以二进制方式打开文件
fileReader.readAsBinaryString(file.file);
fileReader.onload = event => {
try {
const {result} = event.target;
// 以二进制流方式读取得到整份excel表格对象
const workbook = XLSX.read(result, {type: 'binary'});
// 存储获取到的数据
let data = {};
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for(const sheet in workbook.Sheets) {
let tempData = [];
// esline-disable-next-line
if(workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 转成 json 数据
console.log(sheet);
data[sheet] = tempData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
}
}
const excelData = data.Sheet1;
const excelHeader = [];
// 获取表头
for(const headerAttr in excelData[0]) {
const header = {
title: headerAttr,
dataIndex: headerAttr,
key: headerAttr
};
excelHeader.push(header);
}
// 最终获取到并且格式化后的 json 数据
this.setState({
tableData: excelData,
tableHeader: excelHeader,
});
console.log(this.state);
} catch(e) {
// 这里可以抛出文件类型错误不正确的相关提示
console.log(e);
message.error('文件类型不正确!');
}
};
}
}
export default UploadFile;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于React 全面解析excel文件的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did120820