日常开发中,难免遇到需要导入导出的业务场景,特别是一些一对多的场景,如一个用户拥有多个科目,每个科目的成绩不一样。每个人的科目数不相等。
如果直接操作POI的接口实现,代码繁琐且容易出错。
今天在这里给大家推荐一款非常好用的 Excel 导入导出工具工具: zouzhiy-excel 。可以实现复杂的一对多导入导出功能,希望能给予到您帮助!
zouzhiy-excel 简介
zouzhiy-excel 是一款 Excel 导入导出的轻量级工具。对 POI 的接口做了一层封装,使导入导出更加简便快捷。
Spring 环境下集成
<dependency>
<groupId>io.github.zouzhiy</groupId>
<artifactId>zouzhiy-excel-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
开始使用
今天来以用户对应多个课程的成绩为例,介绍一下一对多导入导出的实现。
复杂导出
- 首先创建一对多的数据对象
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ExcelClass
public class OneToManyCustomVO {
private String username;
private String tel;
private Integer age;
private LocalDate birthDay;
private BigDecimal score;
@ExcelField(colspan = 2, cellHandler = ListOneToManyItemStringSplitHandler.class)
private List<OneToManyItemVO> itemList;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OneToManyItemVO {
private String itemName;
private BigDecimal itemScore;
}
此处涉及到复杂表头,可选的实现方式是代码自定义实现,或者模板导出。代码自定义实现,我们只需要实现 RowHeadWrite 接口即可。
为了简便,本文示例我们选择模板方式。
模板表头如下:
- 下一步我们需要实现自定义的CellHandler
@Component
public class ListOneToManyItemStringSplitHandler extends AbstractListSplitHandler<OneToManyItemVO> {
@Override
public ExcelType getExcelType() {
return ExcelType.STRING;
}
}
@Component
public class OneToManyItemStringCellHandler implements CellHandler<OneToManyItemVO> {
@Override
public Class<OneToManyItemVO> getJavaType() {
return OneToManyItemVO.class;
}
@Override
public ExcelType getExcelType() {
return ExcelType.STRING;
}
@Override
public OneToManyItemVO read(SheetContext sheetContext, ExcelFieldConfig excelFieldConfig, CellResultSet cellResultSet) {
if (cellResultSet == null) {
return null;
}
if (cellResultSet.isNone()) {
return null;
}
List<CellResult> cellResultList = cellResultSet.getCellResultListList().get(0);
CellResult cellResultFirst = cellResultList.size() > 0 ? cellResultList.get(0) : CellResult.none();
CellResult cellResultSecond = cellResultList.size()