spring boot 导入excel数据到mysql

https://blog.csdn.net/zhengxiangwen/article/details/68484857

1、引入依赖jar包。

在pom.xml中引入两个依赖的包即可:

1

2

3

4

5

6

7

8

9

10

11

<dependency>

    <groupId>org.apache.poi</groupId>

    <artifactId>poi</artifactId>

    <version>RELEASE</version>

</dependency>

<dependency>

    <groupId>org.apache.poi</groupId>

    <artifactId>poi-ooxml</artifactId>

    <version>RELEASE</version>

</dependency>

下面代码 需要调整部分需要手动删取

例如 参数 HttpServletRequest request,HttpServletResponse response,HttpSession session, 完全可以去掉 等等

二、controller

 
  1. //导入

  2. @PostMapping(value = "batchImport")

  3. public String batchImportUserKnowledge(@RequestParam(value="filename") MultipartFile file,

  4. HttpServletRequest request,HttpServletResponse response,HttpSession session,

  5. @SessionAttribute(Constants.ACCOUNT_SESSION_KEY) Account account) throws IOException{

  6.  
  7. //判断文件是否为空

  8. if(file==null){

  9. session.setAttribute("msg","文件不能为空!");

  10. return "redirect:toUserKnowledgeImport";

  11. }

  12.  
  13. //获取文件名

  14. String fileName=file.getOriginalFilename();

  15.  
  16. //验证文件名是否合格

  17. if(!ExcelImportUtils.validateExcel(fileName)){

  18. session.setAttribute("msg","文件必须是excel格式!");

  19. return "redirect:toUserKnowledgeImport";

  20. }

  21.  
  22. //进一步判断文件内容是否为空(即判断其大小是否为0或其名称是否为null)

  23. long size=file.getSize();

  24. if(StringUtils.isEmpty(fileName) || size==0){

  25. session.setAttribute("msg","文件不能为空!");

  26. return "redirect:toUserKnowledgeImport";

  27. }

  28.  
  29. //批量导入

  30. String message = knowledgeService.batchImport(fileName,file,account.getUsername());

  31. session.setAttribute("msg",message);

  32. return "redirect:toUserKnowledgeImport";

  33. }


三、service层

 
  1. /**

  2. * 上传excel文件到临时目录后并开始解析

  3. * @param fileName

  4. * @param file

  5. * @param userName

  6. * @return

  7. */

  8. public String batchImport(String fileName,MultipartFile mfile,String userName){

  9.  
  10. File uploadDir = new File("E:\\fileupload");

  11. //创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)

  12. if (!uploadDir.exists()) uploadDir.mkdirs();

  13. //新建一个文件

  14. File tempFile = new File("E:\\fileupload\\" + new Date().getTime() + ".xlsx");

  15. //初始化输入流

  16. InputStream is = null;

  17. try{

  18. //将上传的文件写入新建的文件中

  19. mfile.transferTo(tempFile);

  20.  
  21. //根据新建的文件实例化输入流

  22. is = new FileInputStream(tempFile);

  23.  
  24. //根据版本选择创建Workbook的方式

  25. Workbook wb = null;

  26. //根据文件名判断文件是2003版本还是2007版本

  27. if(ExcelImportUtils.isExcel2007(fileName)){

  28. wb = new XSSFWorkbook(is);

  29. }else{

  30. wb = new HSSFWorkbook(is);

  31. }

  32. //根据excel里面的内容读取知识库信息

  33. return readExcelValue(wb,userName,tempFile);

  34. }catch(Exception e){

  35. e.printStackTrace();

  36. } finally{

  37. if(is !=null)

  38. {

  39. try{

  40. is.close();

  41. }catch(IOException e){

  42. is = null;

  43. e.printStackTrace();

  44. }

  45. }

  46. }

  47. return "导入出错!请检查数据格式!";

  48. }

  49.  
  50.  
  51. /**

  52. * 解析Excel里面的数据

  53. * @param wb

  54. * @return

  55. */

  56. private String readExcelValue(Workbook wb,String userName,File tempFile){

  57.  
  58. //错误信息接收器

  59. String errorMsg = "";

  60. //得到第一个shell

  61. Sheet sheet=wb.getSheetAt(0);

  62. //得到Excel的行数

  63. int totalRows=sheet.getPhysicalNumberOfRows();

  64. //总列数

  65. int totalCells = 0;

  66. //得到Excel的列数(前提是有行数),从第二行算起

  67. if(totalRows>=2 && sheet.getRow(1) != null){

  68. totalCells=sheet.getRow(1).getPhysicalNumberOfCells();

  69. }

  70. List<UserKnowledgeBase> userKnowledgeBaseList=new ArrayList<UserKnowledgeBase>();

  71. UserKnowledgeBase tempUserKB;

  72.  
  73. String br = "<br/>";

  74.  
  75. //循环Excel行数,从第二行开始。标题不入库

  76. for(int r=1;r<totalRows;r++){

  77. String rowMessage = "";

  78. Row row = sheet.getRow(r);

  79. if (row == null){

  80. errorMsg += br+"第"+(r+1)+"行数据有问题,请仔细检查!";

  81. continue;

  82. }

  83. tempUserKB = new UserKnowledgeBase();

  84.  
  85. String question = "";

  86. String answer = "";

  87.  
  88. //循环Excel的列

  89. for(int c = 0; c <totalCells; c++){

  90. Cell cell = row.getCell(c);

  91. if (null != cell){

  92. if(c==0){

  93. question = cell.getStringCellValue();

  94. if(StringUtils.isEmpty(question)){

  95. rowMessage += "问题不能为空;";

  96. }else if(question.length()>60){

  97. rowMessage += "问题的字数不能超过60;";

  98. }

  99. tempUserKB.setQuestion(question);

  100. }else if(c==1){

  101. answer = cell.getStringCellValue();

  102. if(StringUtils.isEmpty(answer)){

  103. rowMessage += "答案不能为空;";

  104. }else if(answer.length()>1000){

  105. rowMessage += "答案的字数不能超过1000;";

  106. }

  107. tempUserKB.setAnswer(answer);

  108. }

  109. }else{

  110. rowMessage += "第"+(c+1)+"列数据有问题,请仔细检查;";

  111. }

  112. }

  113. //拼接每行的错误提示

  114. if(!StringUtils.isEmpty(rowMessage)){

  115. errorMsg += br+"第"+(r+1)+"行,"+rowMessage;

  116. }else{

  117. userKnowledgeBaseList.add(tempUserKB);

  118. }

  119. }

  120.  
  121. //删除上传的临时文件

  122. if(tempFile.exists()){

  123. tempFile.delete();

  124. }

  125.  
  126. //全部验证通过才导入到数据库

  127. if(StringUtils.isEmpty(errorMsg)){

  128. for(UserKnowledgeBase userKnowledgeBase : userKnowledgeBaseList){

  129. this.saveUserKnowledge(userKnowledgeBase, userName);

  130. }

  131. errorMsg = "导入成功,共"+userKnowledgeBaseList.size()+"条数据!";

  132. }

  133. return errorMsg;

  134. }

四、工具类代码:

 
  1. public class ExcelImportUtils {

  2.  
  3.  
  4. // @描述:是否是2003的excel,返回true是2003

  5. public static boolean isExcel2003(String filePath) {

  6. return filePath.matches("^.+\\.(?i)(xls)$");

  7. }

  8.  
  9. //@描述:是否是2007的excel,返回true是2007

  10. public static boolean isExcel2007(String filePath) {

  11. return filePath.matches("^.+\\.(?i)(xlsx)$");

  12. }

  13.  
  14. /**

  15. * 验证EXCEL文件

  16. * @param filePath

  17. * @return

  18. */

  19. public static boolean validateExcel(String filePath){

  20. if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){

  21. return false;

  22. }

  23. return true;

  24. }

  25.  
  26.  
  27. }


六、对应的excel内容如下:

猜你喜欢

转载自blog.csdn.net/qq_25600055/article/details/81352508