• springboot导入excel(POI)


    POI官方文档

    引入依赖

    1. <!--POI-->
    2. <dependency>
    3. <groupId>org.apache.poi</groupId>
    4. <artifactId>poi</artifactId>
    5. <version>4.1.2</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>org.apache.poi</groupId>
    9. <artifactId>poi-ooxml</artifactId>
    10. <version>4.1.2</version>
    11. </dependency>
    12. <dependency>
    13. <groupId>org.apache.poi</groupId>
    14. <artifactId>poi-ooxml-schemas</artifactId>
    15. <version>4.1.2</version>
    16. </dependency>

    编写导入工具类

            结合springboot导出(POI)用到的自定义注解,让导入使用起来更方便简洁且更容易扩展。

    1. public class ExcelImportUtil {
    2. /*
    3. * @description: 读取excel数据
    4. * @create: 2023/9/20 16:12
    5. * @param file
    6. * @param tClass
    7. * @return java.util.List
    8. */
    9. public static List readExcel(MultipartFile file, Class tClass){
    10. if(file.isEmpty()){
    11. return new ArrayList<>();
    12. }
    13. //获取列名与属性名的映射
    14. Map feildMap = getFeildMap(tClass);
    15. if(ObjectUtils.isEmpty(feildMap)){
    16. return new ArrayList<>();
    17. }
    18. InputStream inputStream = null;
    19. Workbook workbook = null;
    20. try {
    21. //解析文件
    22. inputStream = file.getInputStream();
    23. workbook = new XSSFWorkbook(inputStream);
    24. Sheet sheet = workbook.getSheetAt(0);
    25. int lastRowNum = sheet.getLastRowNum();
    26. int lastCellNum = sheet.getRow(0).getLastCellNum();
    27. //解析表头
    28. Row headerRow = sheet.getRow(0);
    29. List headerNameList = new ArrayList<>();
    30. for (int i = 0; i < lastCellNum; i++) {
    31. headerNameList.add(headerRow.getCell(i).getStringCellValue());
    32. }
    33. //读取数据
    34. List> dataList = new ArrayList<>();
    35. for (int i = 1; i <= lastRowNum; i++) {
    36. Row row = sheet.getRow(i);
    37. Map rowValueMap = new HashMap<>();
    38. for (int j = 0; j < lastCellNum; j++) {
    39. String key = feildMap.get(headerNameList.get(j));
    40. Object value = getCellValue(row.getCell(j));
    41. rowValueMap.put(key, value);
    42. }
    43. dataList.add(rowValueMap);
    44. }
    45. workbook.close();
    46. inputStream.close();
    47. List list = convertToList(dataList);
    48. return list;
    49. } catch (IOException e) {
    50. e.printStackTrace();
    51. }finally {
    52. try {
    53. if(workbook != null){
    54. workbook.close();
    55. }
    56. if(inputStream !=null){
    57. inputStream.close();
    58. }
    59. } catch (IOException e) {
    60. e.printStackTrace();
    61. }
    62. }
    63. return new ArrayList<>();
    64. }
    65. /*
    66. * @description: 解析导入的实体,获取列名与属性名的映射
    67. * @create: 2023/9/20 16:27
    68. * @param tClass
    69. * @return java.util.Map
    70. */
    71. private static Map getFeildMap(Class tClass){
    72. Field[] fields = tClass.getDeclaredFields();
    73. if(ObjectUtils.isEmpty(fields)){
    74. return null;
    75. }
    76. Map keyMap = new HashMap<>();
    77. for(Field field : fields){
    78. ExcelField excelField = field.getAnnotation(ExcelField.class);
    79. if(ObjectUtils.isNotEmpty(excelField)){
    80. keyMap.put(excelField.name(), field.getName());
    81. }
    82. }
    83. return keyMap;
    84. }
    85. /*
    86. * @description: 获取单元格的值
    87. * @create: 2023/9/20 16:47
    88. * @param cell
    89. * @return java.lang.Object
    90. */
    91. private static Object getCellValue(Cell cell){
    92. if(cell == null){
    93. return null;
    94. }
    95. CellType cellType = cell.getCellType();
    96. if(cellType.equals(CellType.BLANK)){
    97. return null;
    98. }
    99. //字符串
    100. if (cellType.equals(CellType.STRING)){
    101. return cell.getStringCellValue();
    102. }
    103. if(cellType.equals(CellType.NUMERIC)){
    104. //日期
    105. if(HSSFDateUtil.isCellDateFormatted(cell)){
    106. return cell.getDateCellValue();
    107. }else{
    108. //数值
    109. return cell.getNumericCellValue();
    110. }
    111. }
    112. //布尔
    113. if(cellType.equals(CellType.BOOLEAN)){
    114. return cell.getBooleanCellValue();
    115. }
    116. return null;
    117. }
    118. /*
    119. * @description: 转list
    120. * @create: 2023/9/20 17:54
    121. * @param obj
    122. * @return java.util.List
    123. */
    124. private static List convertToList(Object obj){
    125. ObjectMapper objectMapper = new ObjectMapper();
    126. //日期格式
    127. objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    128. //设置时区
    129. objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
    130. //序列化-忽略null值的属性
    131. objectMapper.setSerializationInclusion(Include.NON_NULL);
    132. //序列化-允许序列化空对象
    133. objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    134. //反序列化-在遇到未知属性的时候不抛出异常
    135. objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    136. if(null == obj){
    137. return null;
    138. }
    139. return objectMapper.convertValue(obj, new TypeReference>() {});
    140. }
    141. }

    测试

    导入模板

    导入的泛型(对象)

    1. @Data
    2. public class ImportTest {
    3. @ExcelField(name = "字符串")
    4. private String feild1;
    5. @ExcelField(name = "数值")
    6. private BigDecimal feild2;
    7. @ExcelField(name = "布尔")
    8. private Boolean feild3;
    9. @ExcelField(name = "日期")
    10. private Date feild4;
    11. }

    controller

    1. @Api(tags = "测试")
    2. @RestController
    3. @RequestMapping("/test")
    4. public class TestController {
    5. @ApiOperation("导入")
    6. @PostMapping("/importExcel")
    7. public ResponseEntity> importExcel(@ApiParam(name = "file") @RequestPart("file") MultipartFile file){
    8. List list = ExcelImportUtil.readExcel(file, ImportTest.class);
    9. System.out.print(list);
    10. return ResponseEntity.ok(list);
    11. }
    12. }

    response 

  • 相关阅读:
    CH573/CH571低功耗集成BLE 32位微控制器MCU
    通过okhttp调用SSE流式接口,并将消息返回给客户端
    人类的智能是可变的
    linux 4.19 ip重组
    notepad++设置中文界面
    Java8 BiConsumer<T, U> 函数接口浅析分享(含示例,来戳!)
    用ffmpeg删除视频的音轨,让视频静音
    版本控制--Git
    文举论金:黄金原油全面走势分析策略独家指导
    vue的响应式原理:依赖追踪
  • 原文地址:https://blog.csdn.net/lizsy/article/details/133134118