1、问题描述
因某些特殊原因需要在EasyExcel对应的excel实体类中使用自定义Converter,一开始将excel表格对应列设置成文本格式没有任何问题,但后来由于业务需要将对应列设置成日期格式,在使用自定义Converter发现cellData.getStringValue()一直为空,打断点发现导入的数据是NUMBER类型(如下图所示),一下则是就如何解决NUMBER类型数据提供的方案。
2、解决方法
参考链接:https://github.com/alibaba/easyexcel/issues/693
3、代码实现
@Slf4j
public class DateFormatConverter implements Converter<Date> {
@Override
public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
//单元格格式为 文本类型
if (CellDataTypeEnum.STRING.equals(cellData.getType())) {
DateTime time = null;
try {
// hutool工具类解析日期
time = DateUtil.parse(cellData.getStringValue());
} catch (Exception e) {
log.error("hutool DateUtil.parse error: ", e);
//可以抛异常,也可以返回空,看业务需求需要如何处理
}
return time;
}
//单元格格式为 日期类型 参考 com.alibaba.excel.converters.date.DateNumberConverter
if (CellDataTypeEnum.NUMBER.equals(cellData.getType())) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return DateUtils.getJavaDate(cellData.getNumberValue().doubleValue(),
globalConfiguration.getUse1904windowing());
} else {
return DateUtils.getJavaDate(cellData.getNumberValue().doubleValue(),
contentProperty.getDateTimeFormatProperty().getUse1904windowing());
}
}
return null;
}
}