1.使用工具:xlsx
2.功能说明:将excel文件数据导入到页面上进行渲染
3.文件上传我用的是antd的Upload.Dragger
<Modal
title="Excel表格导入"
visible={uploadVisible}
maskClosable={false}
closable={false}
destroyOnClose
footer={
<div style={{textAlign:"center",position:"relative"}}>
<Button type={"primary"} onClick={this.closeModal}>取消</Button>
<Button type={"primary"} onClick={this.importFile}>导入文件</Button>
</div>
}
>
<Dragger
name='file'
accept=".xls,.csv,.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
beforeUpload={this.beforeUpload}
onChange={this.changeUpload}
onRemove={this.onRemove}
showUploadList={true}
fileList={fileList}
disabled={fileList.length?true:false}
>
<p className="ant-upload-drag-icon"><Icon type="inbox" /></p>
<p className="ant-upload-text">请点击选择文件</p>
<p className="ant-upload-hint">仅支持.xls或.xlsx文件类型</p>
</Dragger>
<RadioGroup defaultValue={1} style={{marginTop:'5px'}} onChange={this.radioChange}>
<Radio value={1}>携带表头</Radio>
<Radio value={2}>不携带表头</Radio>
</RadioGroup>
</Modal>
3.在beforeUpload中对文件数据进行二进制处理
beforeUpload=(file,fileList)=>{
const files = fileList[0];
const rABS = true; //是否将文件读取为二进制字符串
const fileReader = new FileReader();
let that = this;
fileReader.onload = function (e) {
let data = e.target.result;
if (!rABS) data = new Uint8Array(data);
let workbook = XLSX.read(data,{type: rABS ? "binary" : "array" });
let first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
let jsonArr = XLSX.utils.sheet_to_json(first_worksheet,{header:1});
that.handleData(jsonArr,'add');
};
if (rABS) fileReader.readAsBinaryString(files); else fileReader.readAsArrayBuffer(files);
}
// 处理数据
handleData=(data,type)=>{
if (type === 'add') {
// 携带表头时去掉表头
if (this.state.radioValue === '1') {
data.splice(0,1);
}
this.setState({excelData:this.state.excelData.concat(data)})
} else {
//由于只支持单个文件上传 所以直接清空excelData
this.setState({excelData:[]})
}
}
// 处理状态
changeUpload=(info)=>{
const {file,fileList} = info
this.setState({fileList})
const status = file.status;
if (status === 'done') {
message.success(`${file.name}上传成功.`);
} else if (status === 'error') {
message.error(`${file.name}上传失败.`);
}
}
4.导入数据到页面的数据处理
// 导入文件
importFile = () => {
const {excelData} = this.state;
if(excelData.length) {
let columnArr = [],resultData = [];
// 1.根据获取到的表头数据提取ID
this.props.columnDefs.map((item)=>{
// 2.剔除额外的列
if(item.field.indexOf('@') === -1){
columnArr.push(item.field)
}
})
// 3.遍历每行的数据
excelData.map((item)=>{
let obj = {};
//4.重新组织每行的数据
for(let i =0;i<item.length;i++){
obj[columnArr[i]]=item[i]
}
// 6.返回组织的结果数据
resultData.push(obj)
})
/*文件数据OUT*/
this.props.getFileData(resultData);
} else {
message.warn("请先上传文件")
}
}