Springboot上传excel并将表格数据导入或更新mySql数据库的过程
本文主要描述,Springboot-mybatis框架下上传excel,并将之导入mysql数据库的过程,如果用户id已存在,则进行更新修改数据库中该项信息,由于用到的是前后端分离技术,这里记录的主要是后端java部分,通过与前端接口进行对接实现功能,使用layui等前端框架与之对接,也可以自己写前端代码,本文以Controller开始,从导入过程开始讲述,其中包括字典表的转换
1.在pom.xml文件中导入注解,主要利用POI
org.apache.poi poi-ooxml 3.9 commons-fileupload commons-fileupload 1.3.1 commons-io commons-io 2.4
2.Controller接口
@PostMapping("/save")
publicStringaddUser(@RequestParam("file")MultipartFilefile){
StringfileName=file.getOriginalFilename();
try{
returnsysService.batchImport(fileName,file);
}catch(MyExceptione){
e.printStackTrace();
returne.getMessage();
}catch(Exceptione){
e.printStackTrace();
return"文件异常,导入失败";
}
}
3.服务层接口
booleanimport(StringfileName,MultipartFilefile)throwsException;
4.业务层实现类
@Transactional(readOnly=false,rollbackFor=Exception.class)
@Override
publicbooleanimport(StringfileName,MultipartFilefile)throwsException{
MapdepartmentMap=findDepartment();
MaproleMap=findRole();
booleannotNull=false;
ListuserList=newArrayList();
if(!fileName.matches("^.+\\.(?i)(xls)$")&&!fileName.matches("^.+\\.(?i)(xlsx)$")){
thrownewMyException("上传文件格式不正确");
}
booleanisExcel2003=true;
if(fileName.matches("^.+\\.(?i)(xlsx)$")){
isExcel2003=false;
}
InputStreamis=file.getInputStream();
Workbookwb=null;
if(isExcel2003){
wb=newHSSFWorkbook(is);
}else{
wb=newXSSFWorkbook(is);
}
Sheetsheet=wb.getSheetAt(0);
if(sheet!=null){
notNull=true;
}
Useruser;
for(intr=1;r<=sheet.getLastRowNum();r++){
Rowrow=sheet.getRow(r);
if(row==null){
continue;
}
user=newUser();
if(row.getCell(0).getCellType()!=1){
thrownewMyException("导入失败(第"+(r+1)+"行,ID单元格格式请设为文本格式)");
}
Stringid=row.getCell(0).getStringCellValue();
if(id==null||id.isEmpty()){
thrownewMyException("导入失败(第"+(r+1)+"行,ID未填写)");
}
Stringname=row.getCell(1).getStringCellValue();
if(name==null||name.isEmpty()){
thrownewMyException("导入失败(第"+(r+1)+"行,姓名未填写)");
}
Stringdepartment=row.getCell(2).getStringCellValue();
if(departmentMap.get(department)==null){
thrownewMyException("导入失败(第"+(r+1)+"行,不存在此单位或单位未填写)");
}
Stringrole=row.getCell(3).getStringCellValue();
if(roleMap.get(role)==null){
thrownewMyException("导入失败(第"+(r+1)+"行,不存在此角色或角色未填写)");
}
Datedate;
if(row.getCell(4).getCellType()!=0){
thrownewMyException("导入失败(第"+(r+1)+"行,入职日期格式不正确或未填写)");
}else{
date=row.getCell(4).getDateCellValue();
}
user.setId(id);
user.setName(name);
user.setDepartmentId((int)departmentMap.get(department));
user.setRoleId((int)roleMap.get(role));
user.setDate(date);
userList.add(user);
}
for(Useruser:userList){
Stringid=user.getId();
intcnt=userMapper.selectById(id);
if(cnt==0){
userMapper.addUser(user);
}else{
userMapper.updateUserById(user);
}
}
returnnotNull;
}
总结
以上所述是小编给大家介绍的Springboot上传excel并将表格数据导入或更新mySql数据库,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。