目录
介绍
Poiji 依赖介绍
核心功能
典型使用场景
版本说明
代码实战
添加依赖
测试文件
代码
介绍
在博主之前的文章中,博主介绍了几个导入和导出excel的方法,其中对于复杂表头,之前博主文章里虽然也有介绍,但是实现方法并不够简洁,下面将介绍下如何使用poiji来极简方式处理复杂excel数据的处理。
Poiji 依赖介绍
Poiji 是一个轻量级的 Java 库,专门用于将 Excel 文件(.xls 和 .xlsx)快速转换为 Java 对象。它通过注解驱动的方式简化了 Excel 数据的解析过程,非常适合需要处理大量 Excel 数据的场景。
核心功能
- 注解驱动映射:通过
@ExcelCell、@ExcelRow等注解将 Excel 列与 Java 对象的字段直接关联。 - 支持多种数据类型:自动处理字符串、数字、日期等常见类型的转换。
- 高性能解析:基于 Apache POI 实现,优化了大数据量的处理效率。
典型使用场景
- 批量导入 Excel 数据到数据库。
- 快速将 Excel 报表转换为 Java 对象进行业务处理。
- 自动化测试中解析测试数据。
版本说明
当前最新稳定版本为 5.2.0(2024年发布),兼容 Java 8 及以上版本。该版本修复了早期版本中对动态列处理的缺陷,并优化了内存管理。
代码实战
添加依赖
首先在项目中引入我们所需的依赖
<dependency> <groupId>com.github.ozlerhakan</groupId> <artifactId>poiji</artifactId> <version>5.2.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>其中lombok是博主开发习惯使用了,各位可以根据自己的开发习惯选择是否使用
测试文件
新复杂表头的测试文件
代码
根据excel文件的sheet表数据,我们进行分析,建立java的实体映射
这个例子中就可以分析出,创建三个实体PersonCreditInfo是外层最大的,然后包含两个子类CardInfo和PersonInfo
CardInfo
import com.poiji.annotation.ExcelCellName; import lombok.Data; @Data public class CardInfo { @ExcelCellName("类型") private String type; @ExcelCellName("末尾号码") private String last4Digits; @ExcelCellName("有效期") private String expirationDate; }PersonInfo
import 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; }PersonCreditInfo
import 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(); List<PersonCreditInfo> 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文件的可以查看博主之前的文章进行实现