import React from "react";
import ReactDOM from ‘react-dom‘
import * as XLSX from ‘xlsx‘;
import {Button, message, Table,Upload} from ‘antd‘;
import ExportJsonExcel from ‘js-export-excel‘;
import ‘antd/dist/antd.css‘;
const Dragger = Upload.Dragger;
class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],//表格内容
columns: [],//表格头部
data:[]//excel数据
};
}
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‘ });
console.log(workbook)
// 存储获取到的数据
let data = {
};
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for (const sheet in workbook.Sheets) {
let tempData = [];
// esline-disable-next-line
// console.log(workbook.Sheets[sheet])
if (workbook.Sheets.hasOwnProperty(sheet)) {
console.log(sheet)
// 利用 sheet_to_json 方法将 excel 转成 json 数据
data[sheet] = tempData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
}
}
console.log(data)
//上传成功啦,data为上传后的数据
this.setState({
data:data.Sheet1
});
// 最终获取到并且格式化后的 json 数据
message.success(‘上传成功!‘)
} catch (e) {
// 这里可以抛出文件类型错误不正确的相关提示
message.error(‘文件类型不正确!‘);
}
let columns = [];
let dataSource = [];
let keys = Object.keys(this.state.data[0]);
columns = keys.map((item,index)=>{
return {
title:item,
dataIndex:item,
key:item
}
});
dataSource = this.state.data.map((item,index)=>{
return {
key:index.toString(),
"规则协议":item["规则协议"],
"端口":item["端口"],
"来源":item["来源"],
"策略":item["策略"],
"备注":item["备注"],
"修改时间":item["修改时间"]
}
})
this.setState({
columns,
dataSource,
})
};
// 以二进制方式打开文件
}
render() {
const {columns,dataSource} = this.state
return (
<div>
<Dragger name="file"
beforeUpload={function () {
return false;
}}
onChange={this.uploadFilesChange.bind(this)}
showUploadList={false}>
<p className="ant-upload-text">
<span>点击上传文件</span>
或者拖拽上传
</p>
</Dragger>
123131
<Button type="primary" onClick={this.downloadFileToExcel} style={{ marginBottom: "15px" }}>下载</Button>
<Table columns={columns} dataSource={dataSource}/>
</div>
);
}
}
ReactDOM.render(<Index/>,document.getElementById(‘root‘))