登录
首页 >  数据库 >  MySQL

如何使用Spring Boot上传Excel并将数据导入或更新到MySQL数据库?

来源:亿速云

时间:2023-04-29 08:26:33 321浏览 收藏

今天golang学习网给大家带来了《如何使用Spring Boot上传Excel并将数据导入或更新到MySQL数据库?》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

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") 
public String addUser(@RequestParam("file") MultipartFile file) { 
 String fileName = file.getOriginalFilename(); 
 try { 
  return sysService.batchImport(fileName, file); 
 } catch (MyException e) { 
  e.printStackTrace(); 
  return e.getMessage(); 
 }catch(Exception e){ 
  e.printStackTrace(); 
  return "文件异常,导入失败"; 
   
 } 
}

3.服务层接口

boolean import(String fileName, MultipartFile file) throws Exception;

4.业务层实现类

@Transactional(readOnly = false,rollbackFor = Exception.class) 
@Override 
public boolean import(String fileName, MultipartFile file) throws Exception { 
 Map departmentMap = findDepartment(); 
 Map roleMap = findRole(); 
 boolean notNull = false; 
  List userList = new ArrayList(); 
 if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { 
   throw new MyException("上传文件格式不正确"); 
 } 
 boolean isExcel2003 = true; 
 if (fileName.matches("^.+\\.(?i)(xlsx)$")) { 
  isExcel2003 = false; 
 } 
 InputStream is = file.getInputStream(); 
  Workbook wb = null; 
  if (isExcel2003) { 
   wb = new HSSFWorkbook(is); 
  } else { 
   wb = new XSSFWorkbook(is); 
  } 
  Sheet sheet = wb.getSheetAt(0); 
  if(sheet!=null){ 
   notNull = true; 
  } 
 User user; 
 for (int r = 1; r             

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何使用Spring Boot上传Excel并将数据导入或更新到MySQL数据库?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:亿速云 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表