Fork me on GitHub

使用XLSL读取excel表格

使用插件 XLSX 前端读取 excel,转为 table 数据
https://github.com/SheetJS/js-xlsx

  • 安装
1
npm i --save xlsx
  • 引入
1
import  XLSX from 'xlsx';
  • 上传组件
1
2
3
4
5
6
7
<div className='input'>
<div className='input-file-box'>
<Icon type="upload" /><span style={{paddingLeft:5}}>上传学生表格</span>
</div>
<input type="file" className="form-control" accept={SheetJSFT}
onChange={this.uploadExcel} />
</div>

修改 H5 上传组件的样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.input{
margin-top:10px;
margin-bottom:30px;
position: relative;
width:130px;
height:30px;
}
.form-control{
position: absolute;
opacity:0;
top:0;
right:0;
bottom:0;
left:0;
cursor: pointer;
width:100%;
}
.input-file-box{
border: 1px solid #D9D9D9;
padding: 5px;
position: relative;
text-align: center;
border-radius: 4px;
}

效果类似如下
上传组件样式

  • 功能实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 uploadExcel = (e) => {
this.setState({loading:true})
const files = e.target.files;
if(files && files[0]) this.handleFile(files[0]);
}
handleFile = (file/*:File*/) => {
const reader = new FileReader();
reader.onload = (e) => {
const bstr = e.target.result;
const wb = XLSX.read(bstr, {type:'binary'});//type读取方式为对象key-value,如果type为array,读出来的是数组形式
const wsname = wb.SheetNames[0];//读取第一个sheet
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws);
console.log('data',data)
this.formData(data);
this.setState({ studentForm: data, });
};
reader.readAsBinaryString(file);// 以二进制方式打开文件
}
  • 处理数据,将 key 由文字转为字符串,Table 需要的形式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//表格数据格式化
formData = (data) => {
let id= this.props.location.pathname.split(':')[1];
data.map(line=>{
return Object.keys(line).forEach(function(key){
// console.log(key,line[key]);
switch(key){
case '学号':
line.student_num = line[key];
break;
case '学生姓名':
line.name = line[key];
break;
case '班级':
line.class_name = line[key];
break;
case '院系':
line.college_name = line[key];
break;
case '修读类别':
line.study_type = line[key];
break;
default:
break;
}
delete line[key];
});
})
}
-------------本文结束感谢阅读-------------