在上一篇导出篇我们使用版本2.2.10导出excel,但无法处理null字段拦截。
https://blog.csdn.net/cxj443914930/article/details/123538144
下面我们实现对null字段的拦截处理
升级EasyExcel版本, 3.0.5可以不用导入poi-ooxml、和poi两个包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
转换器IntegerNullableConverter.java
package com.learning.easyexcel.converter;
import com.alibaba.excel.converters.NullableObjectConverter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.math.BigDecimal;
import java.util.Objects;
/**
* null转换
*/
public class IntegerNullableConverter implements NullableObjectConverter<Integer> {
@Override
public Class<Integer> supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
@Override
public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return cellData.getNumberValue().intValue();
}
@Override
public WriteCellData<?> convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if (Objects.isNull(integer)) {
return new WriteCellData<>("-");
} else {
return new WriteCellData<>(BigDecimal.valueOf(integer));
}
}
}
使用注解绑定转换器
@ExcelProperty(value = "测试null值转换", converter = IntegerNullableConverter.class)
// 单元格右对齐(默认int类型右对齐,字符串左对齐)
@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.RIGHT)
private Integer testNull;
生成表格
/**
* 测试null值转换
*/
@Test
public void exportNullColumn() {
Consumer<ExcelWriter> consumer = writer -> {
List<Student> students = generateStudent(2);
students.get(0).setTestNull(100);
writer.write(students, EasyExcel.writerSheet("学生信息")
.registerWriteHandler(new FreezeNameHandler()) // 冻结姓名列
.head(Student.class)
.build());
};
export("D:/报表.xlsx", consumer);
}
效果