java使用POI导入excel并记录一个读取xlsx报错

  • java使用POI导入Excel ,工具类直接上代码

    • 引入Maven

      xml 复制代码
      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>4.1.2</version>
      </dependency>
      
      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>4.1.2</version>
      </dependency>
      
      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml-schemas</artifactId>
          <version>4.1.2</version>
      </dependency>
      <dependency>
          <groupId>org.apache.xmlbeans</groupId>
          <artifactId>xmlbeans</artifactId>
          <version>3.1.0</version>
      </dependency>
      • 如果不引入xmlbeans的话解析xlsx文件可能会报错:

        • 我遇到的报错内容为:java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions
    • 导入工具类的代码(代码仅供参考,根据自己需求修改,少的引入自行解决):

      Java 复制代码
      package com.zz.bzyw.utils;
      import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
      import com.zz.bzyw.config.common.BzywException;
      import lombok.extern.slf4j.Slf4j;
      import org.apache.commons.lang3.StringUtils;
      import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
      import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      import org.apache.poi.ss.usermodel.*;
      import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
      import org.apache.poi.xssf.usermodel.XSSFWorkbook;
      import org.apache.xmlbeans.impl.xb.xsdschema.Public;
      import org.springframework.web.multipart.MultipartFile;
      
      import java.io.IOException;
      import java.io.InputStream;
      import java.text.DateFormat;
      import java.text.SimpleDateFormat;
      import java.util.*;
      
      /**
       * @author zzsoft
       */
      @Slf4j
      public class ReadExcelUtil {
      
          //读取xls表格
          public static void formatMap2007(List<Map<String, Object>> dataList, Sheet sheetName, XSSFWorkbook workbook){
              int rowTotle = sheetName.getLastRowNum();
              Row title = sheetName.getRow(1);
              Iterator<Cell> titleIte = title.cellIterator();
      
              List<String> titleFields = new ArrayList<>();
              while (titleIte.hasNext()){
                  Cell cell = titleIte.next();
                  String titleField = cell.getStringCellValue();
                  titleFields.add(titleField);
              }
              for (int i = 2; i <= rowTotle; i++) {
                  Map<String, Object> rowMap = new HashMap<>();
                  for (int j = 0; j < titleFields.size(); j++) {
                      try{
                          //获取行数据
                          Row row = sheetName.getRow(i);
                          String rowKey = titleFields.get(j);
                          Cell cloCell = row.getCell(j);
                          if(cloCell != null){
                              /**
                               * 暂时屏蔽 bug SCJZMJ = 62.68 此方法会自动将数值转为72。 暂屏蔽 2022.07.03 Edit.WangZhen
                               * */
      //                        else if ("YCJZMJ".equals(rowKey)){
      //                            cloCell.setCellType(CellType.NUMERIC);
      //                        } else if ("GYTDMJ".equals(rowKey)){
      //                            cloCell.setCellType(CellType.NUMERIC);
      //                        } else if ("SCJZMJ".equals(rowKey)){
      //                            cloCell.setCellType(CellType.NUMERIC);
      //                        }
                              String cellType = cloCell.getCellType().toString();
                              if("STRING".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getStringCellValue());
                              }else if(DateUtil.isCellDateFormatted(cloCell)){
                                  Date date = cloCell.getDateCellValue();
                                  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                  rowMap.put(rowKey,dateFormat.format(date));
                              } else if("NUMERIC".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getNumericCellValue());
                              } else if("BOOLEAN".equals(cellType)){
                                  rowMap.put(rowKey,cloCell.getBooleanCellValue());
                              }else if("FORMULA".equals(cellType)){
                                  XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(workbook);
                                  CellValue cellValue = eva.evaluate(cloCell);
                                  rowMap.put(rowKey, cellValue.getStringValue());
                              }
                          }
                      }catch (Exception exception) {
                          log.info("excel表格读取报错: ", exception);
                      }
                  }
                  if(rowMap.size() > 0){
                      dataList.add(rowMap);
                  }
              }
          }
      
          //读取xlsx表格
          public static void formatMap2003(List<Map<String, Object>> dataList, Sheet sheetName, HSSFWorkbook workbook){
              int rowTotle = sheetName.getLastRowNum();
              Row title = sheetName.getRow(1);
              Iterator<Cell>  titleIte = title.cellIterator();
      
              List<String> titleFields = new ArrayList<>();
              while (titleIte.hasNext()){
                  Cell cell = titleIte.next();
                  String titleField = cell.getStringCellValue();
                  titleFields.add(titleField);
              }
              for (int i = 2; i <= rowTotle; i++) {
                  Map<String, Object> rowMap = new HashMap<>();
                  for (int j = 0; j < titleFields.size(); j++) {
                      try{
                          //获取行数据
                          Row row = sheetName.getRow(i);
                          String rowKey = titleFields.get(j);
                          Cell cloCell = row.getCell(j);
                          if(cloCell != null){
                              String cellType = cloCell.getCellType().toString();
                              if("STRING".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getStringCellValue());
                              }else if(DateUtil.isCellDateFormatted(cloCell)){
                                  Date date = cloCell.getDateCellValue();
                                  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                  rowMap.put(rowKey,dateFormat.format(date));
                              } else if("NUMERIC".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getNumericCellValue());
                              } else if("BOOLEAN".equals(cellType)){
                                  rowMap.put(rowKey,cloCell.getBooleanCellValue());
                              }else if("FORMULA".equals(cellType)){
                                  HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(workbook);
                                  CellValue cellValue = eva.evaluate(cloCell);
                                  rowMap.put(rowKey, cellValue.getStringValue());
                              }
                          }
                      }catch (Exception exception) {
                          log.info("excel表格读取报错: ", exception);
                      }
                  }
                  if(rowMap.size() > 0){
                      dataList.add(rowMap);
                  }
              }
          }
      
          //读取xls表格
          public static void read2007(List<Map<String, Object>> dataList, Sheet sheetName, Integer titleRow, XSSFWorkbook workbook){
              int rowTotle = sheetName.getLastRowNum();
              Row title = sheetName.getRow(titleRow);
              Iterator<Cell> titleIte = title.cellIterator();
      
              List<String> titleFields = new ArrayList<>();
              while (titleIte.hasNext()){
                  Cell cell = titleIte.next();
                  String titleField = cell.getStringCellValue();
                  titleFields.add(titleField);
              }
              for (int i = titleRow + 1; i <= rowTotle; i++) {
                  Map<String, Object> rowMap = new HashMap<>();
                  for (int j = 0; j < titleFields.size(); j++) {
                      try{
                          //获取行数据
                          Row row = sheetName.getRow(i);
                          String rowKey = titleFields.get(j);
                          Cell cloCell = row.getCell(j);
                          if(cloCell != null){
                              String cellType = cloCell.getCellType().toString();
                              if("STRING".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getStringCellValue());
                              }else if(DateUtil.isCellDateFormatted(cloCell)){
                                  Date date = cloCell.getDateCellValue();
                                  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                  rowMap.put(rowKey,dateFormat.format(date));
                              } else if("NUMERIC".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getNumericCellValue());
                              } else if("BOOLEAN".equals(cellType)){
                                  rowMap.put(rowKey,cloCell.getBooleanCellValue());
                              }else if("FORMULA".equals(cellType)){
                                  XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(workbook);
                                  CellValue cellValue = eva.evaluate(cloCell);
                                  rowMap.put(rowKey, cellValue.getStringValue());
                              }
                          }
                      }catch (Exception exception) {
                          log.info("excel表格读取报错: ", exception);
                      }
                  }
                  if(rowMap.size() > 0){
                      dataList.add(rowMap);
                  }
              }
          }
      
          //读取xlsx表格
          public static void read2003(List<Map<String, Object>> dataList, Sheet sheetName, Integer titleRow, HSSFWorkbook workbook){
              int rowTotle = sheetName.getLastRowNum();
              Row title = sheetName.getRow(titleRow);
              Iterator<Cell>  titleIte = title.cellIterator();
      
              List<String> titleFields = new ArrayList<>();
              while (titleIte.hasNext()){
                  Cell cell = titleIte.next();
                  String titleField = cell.getStringCellValue();
                  titleFields.add(titleField);
              }
              for (int i = titleRow + 1; i <= rowTotle; i++) {
                  Map<String, Object> rowMap = new HashMap<>();
                  for (int j = 0; j < titleFields.size(); j++) {
                      try{
                          //获取行数据
                          Row row = sheetName.getRow(i);
                          String rowKey = titleFields.get(j);
                          Cell cloCell = row.getCell(j);
                          if(cloCell != null){
                              String cellType = cloCell.getCellType().toString();
                              if("STRING".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getStringCellValue());
                              }else if(DateUtil.isCellDateFormatted(cloCell)){
                                  Date date = cloCell.getDateCellValue();
                                  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                  rowMap.put(rowKey,dateFormat.format(date));
                              } else if("NUMERIC".equals(cellType)){
                                  rowMap.put(rowKey, cloCell.getNumericCellValue());
                              } else if("BOOLEAN".equals(cellType)){
                                  rowMap.put(rowKey,cloCell.getBooleanCellValue());
                              }else if("FORMULA".equals(cellType)){
                                  HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(workbook);
                                  CellValue cellValue = eva.evaluate(cloCell);
                                  rowMap.put(rowKey, cellValue.getStringValue());
                              }
                          }
                      }catch (Exception exception) {
                          log.info("excel表格读取报错: ", exception);
                      }
                  }
                  if(rowMap.size() > 0){
                      dataList.add(rowMap);
                  }
              }
          }
      
          /**
           * 读取excel文件
           * @param file 上传文件
           * @param huMapList 返回数据列表
           * @param sheetName 表格中sheetName
           */
          public static void readExcel(MultipartFile file, List<Map<String, Object>> huMapList, String sheetName, Integer titleRow) {
              try (InputStream stream = file.getInputStream()) {
                  // 检查扩展名
                  String fileName = file.getOriginalFilename();
                  assert fileName != null;
                  String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                  //通过后缀选择不同的表格处理方法
                  if ("xls".equals(fileExt)) {
                      HSSFWorkbook workbook = new HSSFWorkbook(stream);
                      //户
                      Sheet hu = workbook.getSheet(sheetName);
                      if (hu != null) {
                          ReadExcelUtil.read2003(huMapList, hu, titleRow, workbook);
                      } else {
                          throw new BzywException("检查文件中sheet名称是否为:" + sheetName);
                      }
                  } else if ("xlsx".equals(fileExt)) {
                      XSSFWorkbook workbook = new XSSFWorkbook(stream);
                      //户
                      Sheet hu = workbook.getSheet(sheetName);
                      if (hu != null) {
                          ReadExcelUtil.read2007(huMapList, hu, titleRow, workbook);
                      } else {
                          throw new BzywException("检查文件中sheet名称是否为:" + sheetName);
                      }
                  } else {
                      throw new BzywException("文件类型错误:不被允许的文件格式");
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
      }
相关推荐
529宝宝起名网1 小时前
用 Python 开发历史名字查询与起名灵感工具:从古籍人物数据库到名字文化故事生成
开发语言·前端·python
AI深栈1 小时前
第 10 章 · Embedding、VectorStore 与 RAG
java·人工智能
ocean21032 小时前
2025-2026年C++专题大厂面试高频问题
开发语言·c++·面试
Java内核笔记2 小时前
Spring Boot 4 SSRF 防护源码剖析:InetAddressFilter 挡住内网地址与云元数据
java·后端
白远山2 小时前
健身场馆无人自动化系统实战指南:从架构设计到部署全流程解析
java·开发语言·架构·需求分析
user_admin_god2 小时前
第 09 篇:实践一 —— 文本摘要(Map-Reduce 分块)
java·人工智能·spring boot·语言模型
咖啡八杯2 小时前
Controller 基类封装:BaseController 的模板方法设计
java·架构·设计
vx_BS813302 小时前
【项目编号:project49759】Spring Boot 宠物综合服务平台:商城、预约、咨询、活动与健康档案的一体化实现
java·spring boot·eclipse·tomcat·intellij-idea
她的男孩2 小时前
加了 @Idempotent 还是重复扣款了 3 笔:扒完 1279 行幂等 Starter,我挖出 5 个隐蔽的坑
java·后端·架构
步行cgn2 小时前
Spring 注入内部 Bean 详解
java·spring·rpc