mybatis-Plus解析excel表格并添加到数据库

素颜马尾好姑娘i 2023-09-25 17:22 128阅读 0赞

1.首先,创建一个StringBoot项目

2.导入相关依赖:

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi-ooxml</artifactId>
  4. <version>3.17</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi</artifactId>
  9. <version>4.1.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.baomidou</groupId>
  13. <artifactId>mybatis-plus-boot-starter</artifactId>
  14. <version>3.5.2</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>mysql</groupId>
  18. <artifactId>mysql-connector-java</artifactId>
  19. <version>5.1.47</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.projectlombok</groupId>
  23. <artifactId>lombok</artifactId>
  24. </dependency>
  1. application.yaml的配置

    spring:
    datasource:

    1. driver-class-name: com.mysql.jdbc.Driver
    2. url: jdbc:mysql://localhost:3306/student-programmer?useSSL=false&characterEncoding=utf8
    3. username: root
    4. password: root

    servlet:

    1. multipart:
    2. max-file-size: 100MB
    3. max-request-size: 500MB

    mybatis-plus:
    configuration:

    1. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    2. map-underscore-to-camel-case: true

    mapper-locations: classpath:/mapper/**/.xml
    type-aliases-package: cn.java999studentlogin.bean
    server:
    port: 9090

4.创建java实体类

  1. package cn.java999.uploadandparseexcel.entity;
  2. import com.baomidou.mybatisplus.annotation.TableId;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import org.springframework.stereotype.Component;
  7. @Data
  8. @AllArgsConstructor
  9. @NoArgsConstructor
  10. @Component
  11. public class Community {
  12. @TableId
  13. private Integer ID;
  14. private String number;
  15. private String relationship;
  16. private String name;
  17. private String gender;
  18. private String age;
  19. private String Date;
  20. private String card;
  21. private String Mobile;
  22. private String nationality;
  23. private String station;
  24. private String committee;
  25. }

5.创建ExcelUtils工具类

  1. package cn.java999.uploadandparseexcel.Utils;
  2. import cn.java999.uploadandparseexcel.entity.Community;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import org.apache.poi.ss.usermodel.*;
  5. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. public class ExcelUtils {
  13. //总行数
  14. private static int totalRows = 12;
  15. //总条数
  16. private static int totalCells = 12;
  17. //错误信息接收器
  18. private static String errorMsg;
  19. /**
  20. * 验证EXCEL文件
  21. *
  22. * @param filePath
  23. * @return
  24. */
  25. public static boolean validateExcel(String filePath) {
  26. if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
  27. errorMsg = "文件名不是excel格式";
  28. return false;
  29. }
  30. return true;
  31. }
  32. /*
  33. excel2003版本的excel文件是.xls格式,excel2007及以上版本的excel的是.xlsx格式。
  34. */
  35. // @描述:是否是2003的excel,返回true是2003
  36. public static boolean isExcel2003(String filePath) {
  37. return filePath.matches("^.+\\.(?i)(xls)$");
  38. }
  39. //@描述:是否是2007的excel,返回true是2007
  40. public static boolean isExcel2007(String filePath) {
  41. return filePath.matches("^.+\\.(?i)(xlsx)$");
  42. }
  43. /**
  44. * 读取Excel里面客户的信息
  45. * @param wb
  46. * @return
  47. */
  48. private static List<Community> readExcelValue(Workbook wb) {
  49. //默认会跳过第一行标题
  50. // 得到第一个shell
  51. Sheet sheet = wb.getSheetAt(0);
  52. // 得到Excel的行数
  53. totalRows = sheet.getPhysicalNumberOfRows();
  54. // 得到Excel的列数(前提是有行数)
  55. if (totalRows > 1 && sheet.getRow(0) != null) {
  56. totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
  57. }
  58. List<Community> manychoiceList = new ArrayList<Community>();
  59. // 循环Excel行数
  60. for (int r = 1; r < totalRows; r++) {
  61. Row row = sheet.getRow(r);
  62. if (row == null) {
  63. continue;
  64. }
  65. Community community = new Community();
  66. // 循环Excel的列
  67. for (int c = 0; c < totalCells ; c++) {
  68. Cell cell = row.getCell(c);
  69. if (null != cell) {
  70. if (c == 0) { //第一列
  71. //如果是纯数字,将单元格类型转为String
  72. if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  73. double numericCellValue = cell.getNumericCellValue();
  74. community.setID((int)numericCellValue);
  75. }
  76. } else if (c == 1) {
  77. if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  78. cell.setCellType(CellType.STRING);
  79. }
  80. community.setNumber(cell.getStringCellValue());
  81. } else if (c == 2) {
  82. if (cell.getCellTypeEnum() == CellType.STRING) {
  83. String stringCellValue = cell.getStringCellValue();
  84. community.setRelationship(stringCellValue);
  85. }
  86. } else if (c == 3) {
  87. if (cell.getCellTypeEnum() == CellType.STRING) {
  88. String stringCellValue = cell.getStringCellValue();
  89. community.setName(stringCellValue);
  90. }
  91. } else if (c == 4) {
  92. if (cell.getCellTypeEnum() == CellType.STRING) {
  93. String stringCellValue = cell.getStringCellValue();
  94. community.setGender(stringCellValue);
  95. }
  96. } else if (c == 5) {
  97. if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  98. double numericCellValue = cell.getNumericCellValue();
  99. community.setAge(String.valueOf(Integer.valueOf((int) numericCellValue)));
  100. }
  101. } else if (c == 6) {
  102. if (cell.getCellTypeEnum() == CellType.STRING) {
  103. String numericCellValue = cell.getStringCellValue();
  104. community.setCard(numericCellValue);
  105. }
  106. } else if (c == 7) {
  107. if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  108. cell.setCellType(CellType.STRING);
  109. } String numericCellValue = cell.getStringCellValue();
  110. community.setDate(numericCellValue);
  111. } else if (c == 8) {
  112. if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  113. cell.setCellType(CellType.STRING);
  114. }
  115. String numericCellValue = cell.getStringCellValue();
  116. community.setMobile(numericCellValue);
  117. } else if (c == 9) {
  118. if (cell.getCellTypeEnum() == CellType.STRING) {
  119. String stringCellValue = cell.getStringCellValue();
  120. community.setNationality(stringCellValue);
  121. }
  122. } else if (c == 10) {
  123. if (cell.getCellTypeEnum() == CellType.STRING) {
  124. String stringCellValue = cell.getStringCellValue();
  125. community.setStation(stringCellValue);
  126. }
  127. } else if (c == 11) {
  128. if (cell.getCellTypeEnum() == CellType.STRING) {
  129. String stringCellValue = cell.getStringCellValue();
  130. community.setCommittee(stringCellValue);
  131. }
  132. //score属性是int数据类型,转换成int
  133. // manychoice.setScore(Integer.valueOf(cell.getStringCellValue()));
  134. }
  135. }
  136. }
  137. //将excel解析出来的数据赋值给对象添加到list中
  138. manychoiceList.add(community);
  139. }
  140. return manychoiceList;
  141. }
  142. /**
  143. * 根据excel里面的内容读取客户信息
  144. * @param is 输入流
  145. * @param isExcel2003 excel是2003还是2007版本
  146. * @return
  147. * @throws IOException
  148. */
  149. public static List<Community> createExcel(InputStream is, boolean isExcel2003) {
  150. try{
  151. Workbook wb = null;
  152. if (isExcel2003) {
  153. // 当excel是2003时,创建excel2003
  154. wb = new HSSFWorkbook(is);
  155. } else {
  156. // 当excel是2007时,创建excel2007
  157. wb = new XSSFWorkbook(is);
  158. }
  159. // 读取Excel里面客户的信息
  160. List<Community> communityList = readExcelValue(wb);
  161. return communityList;
  162. } catch (IOException e) {
  163. e.printStackTrace();
  164. }
  165. return null;
  166. }
  167. /**
  168. * 读EXCEL文件,获取信息集合
  169. * @return
  170. */
  171. public static List<Community> getExcelInfo(MultipartFile file) {
  172. String files = file.getOriginalFilename();//获取文件名
  173. try {
  174. if (!validateExcel(files)) {// 验证文件名是否合格
  175. return null;
  176. }
  177. boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
  178. if (isExcel2007(files)) {
  179. isExcel2003 = false;
  180. }
  181. List<Community> communityList = createExcel(file.getInputStream(), isExcel2003);
  182. return communityList;
  183. } catch (Exception e) {
  184. e.printStackTrace();
  185. }
  186. return null;
  187. }
  188. }

6.创建mapper

  1. package cn.java999.uploadandparseexcel.mapper;
  2. import cn.java999.uploadandparseexcel.entity.Community;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import org.apache.ibatis.annotations.Mapper;
  5. @Mapper
  6. public interface Communitymapper extends BaseMapper<Community> {
  7. }

7.创建CommunityController

  1. package cn.java999.uploadandparseexcel.controller;
  2. import cn.java999.uploadandparseexcel.Utils.ExcelUtils;
  3. import cn.java999.uploadandparseexcel.entity.Community;
  4. import cn.java999.uploadandparseexcel.mapper.Communitymapper;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.util.List;
  14. @Controller
  15. public class CommunityController {
  16. @Autowired
  17. private Communitymapper communitymapper;
  18. @GetMapping("/aaa")
  19. public String aaa(){
  20. return "kkk.html";
  21. }
  22. @PostMapping("/excelExport")
  23. public void test(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="file",required = false) MultipartFile file) {
  24. List<Community> excelInfo = ExcelUtils.getExcelInfo(file);
  25. for (Community patientInfo : excelInfo) {
  26. System.err.println(patientInfo);
  27. System.err.println("==========");
  28. Integer id = patientInfo.getID();
  29. String relationship = patientInfo.getRelationship();
  30. String number = patientInfo.getNumber();
  31. String name = patientInfo.getName();
  32. String gender = patientInfo.getGender();
  33. String age = patientInfo.getAge();
  34. String date = patientInfo.getDate();
  35. String card = patientInfo.getCard();
  36. String mobile = patientInfo.getMobile();
  37. String nationality = patientInfo.getNationality();
  38. String station = patientInfo.getStation();
  39. String committee = patientInfo.getCommittee();
  40. Community community = new Community();
  41. community.setID(id);
  42. community.setNumber(number);
  43. community.setRelationship(relationship);
  44. community.setName(name);
  45. community.setGender(gender);
  46. community.setAge(age);
  47. community.setDate(date);
  48. community.setCard(card);
  49. community.setMobile(mobile);
  50. community.setNationality(nationality);
  51. community.setStation(station);
  52. community.setCommittee(committee);
  53. System.err.println(age);
  54. int insert = communitymapper.insert(community);
  55. System.err.println(insert);
  56. }
  57. }
  58. }

8.在resource/static目录下创建updateFile.html文件

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form method="post" enctype="multipart/form-data" action="/excelExport">
  9. <input type="file" name="file" value="选择文件"/>
  10. <input type="submit" value="上传"/>
  11. </form>
  12. </body>
  13. </html>

9.excel表格

6d19721ad0fd4e129b951a27423ea2e4.png

10.前端页面展示,选择文件,点击上传

31d0189f479d42aaaed18a8fea1d35a8.png

11.数据库展示

c8bd7a7b3e6e495796dd8f5de6ebc124.png

12.到这里我们这解析excel并添加到数据库就完成了,请各位铁子们多多支持点赞,如有不足之处请评论下方小宁即使更改

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读