EasyExcel转换为枚举、json等其他类型失败
easyexcel能够解决常规的类型转换问题,但是如果我们有特殊类型:枚举、json等等,往往就会报错,需要配置额外的转换器
easyexcel提供了自定义的转换器接口
interface Converter<T>
其中,我们主要需要重写下述内容
提供一个java中的对象类型,返回java支持的类
default Class<?> supportJavaTypeKey() { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); }
返回Excel支持的对象的枚举
default CellDataTypeEnum supportExcelTypeKey() { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); }
将Excel对象转为java对象(后续两个值)
default T convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); }
将java对象转为Excel对象
default WriteCellData<?> convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); }
以枚举类型为例:
public class GEnumsConverter implements Converter<GEnum> { @Override public Class<GEnum> supportJavaTypeKey() { return GenderEnum.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public GEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { // 将Excel数字转换为G Integer value = cellData.getNumberValue().intValue(); for (GEnum g : GEnum.values()) { if (g.getValue().equals(value)) { return gender; } } throw new IllegalArgumentException("不支持的性别值: " + value); } @Override public WriteCellData<?> convertToExcelData(GEnum value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { if (value == null) { return new WriteCellData<>(""); } WriteCellData<Integer> cellData = new WriteCellData<>(value.getValue().toString()); cellData.setType(CellDataTypeEnum.NUMBER); return cellData; } }