ElementUI导入Excel文件
功能介绍
最近用ElementUI做管理系统需要把excel数据导入到系统内,我想这是一个很常见的功能点,把它分享出来,希望对大家有所帮助:)
实现效果
实现步骤
1.定义导入组件
<el-upload
:show-file-list="false"
accept="application/vnd.ms-excel"
action="http://localhost:9000/api/student/upload"
:on-success="fileUploadSuccess"
:on-error="fileUploadError"
:disabled="fileUploadBtnText == '正在导入'"
:before-upload="beforeFileUpload"
style="display: inline; margin-left:10px;"
>
<el-button
type="success"
:icon="uploadBtnIcon"
:loading="fileUploadBtnText == '正在导入'"
><i class="fa fa-lg fa-level-up"></i>{{ fileUploadBtnText }}
</el-button>
</el-upload>
2.定义导入相关方法
- 先是定义2个变量
fileUploadBtnText: “导入数据”,
uploadBtnIcon: “el-icon-upload2”,
fileUploadSuccess() {
this.enabledUploadBtn = true;
this.uploadBtnIcon = "el-icon-upload2";
this.fileUploadBtnText = "导入数据";
this.$message.success("数据导入成功!");
this.getStudentList();
},
fileUploadError() {
this.enabledUploadBtn = true;
this.uploadBtnIcon = "el-icon-upload2";
this.fileUploadBtnText = "导入数据";
},
beforeFileUpload(file) {
this.enabledUploadBtn = false;
this.uploadBtnIcon = "el-icon-loading";
this.fileUploadBtnText = "正在导入";
},
3.定义导入接口
这里以springboot接口为准
@RequestMapping("/upload")
@ResponseBody
public Result<String> uploadFile(MultipartFile file, HttpServletResponse response) {
//解析excel文件
List<ArrayList<String>> rows = ExcelUtil.analysis(file);
List<Student> list = new ArrayList<>();
if(rows.size()>0){
//2.插入数据
Student entity = null;
int size=0;
String gradeName; // 班级名称
Integer gradeId;
for (int i = 0;i<rows.size();i++){
entity = new Student();
List<String> row = rows.get(i);
size = row.size();
// 不足9个列的 补全
for (int j = size; j < 9; j++) {
row.add("");
}
// 学号
entity.setStudentNo(row.get(0));
// 姓名
entity.setStudentName(row.get(1));
entity.setGender(row.get(2).equals("女")?"F":"M");
entity.setIdno(row.get(3));
entity.setPhone(row.get(4));
entity.setAddress(row.get(5));
gradeName = row.get(6);
gradeId = getGradeIdByName(gradeName);
if(gradeId == null){
continue;
}
entity.setGradeId(gradeId);
entity.setEnrollDate(DateUtil.format(row.get(7),"yyyy-MM-dd"));
entity.setRemark(row.get(8));
list.add(entity);
}
}
studentService.saveBatch(list);
return ResultUtil.ok("导入成功!");
}