Java导入复杂Excel表头数据极简实现(代码图文保姆级教程)

📅 发布时间:2026/7/8 2:47:35 👁️ 浏览次数:
Java导入复杂Excel表头数据极简实现(代码图文保姆级教程)
目录介绍Poiji 依赖介绍核心功能典型使用场景版本说明代码实战添加依赖测试文件代码介绍在博主之前的文章中,博主介绍了几个导入和导出excel的方法,其中对于复杂表头,之前博主文章里虽然也有介绍,但是实现方法并不够简洁,下面将介绍下如何使用poiji来极简方式处理复杂excel数据的处理。Poiji 依赖介绍Poiji 是一个轻量级的 Java 库专门用于将 Excel 文件.xls 和 .xlsx快速转换为 Java 对象。它通过注解驱动的方式简化了 Excel 数据的解析过程非常适合需要处理大量 Excel 数据的场景。核心功能注解驱动映射通过ExcelCell、ExcelRow等注解将 Excel 列与 Java 对象的字段直接关联。支持多种数据类型自动处理字符串、数字、日期等常见类型的转换。高性能解析基于 Apache POI 实现优化了大数据量的处理效率。典型使用场景批量导入 Excel 数据到数据库。快速将 Excel 报表转换为 Java 对象进行业务处理。自动化测试中解析测试数据。版本说明当前最新稳定版本为 5.2.02024年发布兼容 Java 8 及以上版本。该版本修复了早期版本中对动态列处理的缺陷并优化了内存管理。代码实战添加依赖首先在项目中引入我们所需的依赖dependency groupIdcom.github.ozlerhakan/groupId artifactIdpoiji/artifactId version5.2.0/version scopecompile/scope /dependency dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId optionaltrue/optional /dependency其中lombok是博主开发习惯使用了,各位可以根据自己的开发习惯选择是否使用测试文件新复杂表头的测试文件代码根据excel文件的sheet表数据,我们进行分析,建立java的实体映射这个例子中就可以分析出,创建三个实体PersonCreditInfo是外层最大的,然后包含两个子类CardInfo和PersonInfoCardInfoimport com.poiji.annotation.ExcelCellName; import lombok.Data; Data public class CardInfo { ExcelCellName(类型) private String type; ExcelCellName(末尾号码) private String last4Digits; ExcelCellName(有效期) private String expirationDate; }PersonInfoimport com.poiji.annotation.ExcelCell; import com.poiji.annotation.ExcelCellName; import lombok.Data; Data public class PersonInfo { ExcelCellName(姓名) private String name; ExcelCellName(年龄) private Integer age; ExcelCellName(城市) private String city; ExcelCellName(省份) private String province; ExcelCellName(邮编) private String zipCode; }PersonCreditInfoimport com.poiji.annotation.ExcelCellName; import com.poiji.annotation.ExcelCellRange; import com.poiji.annotation.ExcelSheet; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; ExcelSheet(Sheet2) Data AllArgsConstructor NoArgsConstructor public class PersonCreditInfo { ExcelCellName(编号) private Integer no; ExcelCellRange private PersonInfo personInfo; ExcelCellRange private CardInfo cardInfo; }可以直接在实体上面直接定义要读取的sheet页注意我这里是把表格数据创建在第二个sheet页里,sheet页名称要根据自己的实际创建来定义测试读取public static void main(String[] args) { File file new File(C:\\Users\\mgl\\Desktop\\文件副本\\test.xlsx); PoijiOptions options PoijiOptions.PoijiOptionsBuilder.settings().headerCount(2) .build(); ListPersonCreditInfo persons Poiji.fromExcel(file, PersonCreditInfo.class, options); System.out.println(persons); // 方案1打印数量确认是否读取成功 System.err.println(读取到了 persons.size() 条数据); for (PersonCreditInfo person : persons) { System.err.println(person); } }启动测试可以看到正常读取到了数据如果在实体处不标记sheet页,也可以在读取文件处进行设置在读取sheet页时,也可以根据sheet页的索引顺序进行读取,注意索引是从0开始,此时上面例子的Sheet2是第二个sheet页,索引就是1前面实体里属性和sheet页的列绑定是通过表头名进行绑定的也可以通过列索引进行绑定,索引从0开始可以看到Poiji 极简的方式就可以实现复杂excel表头的读取数据;至于导出excel文件的可以查看博主之前的文章进行实现