EasyExcel实现Converter接口解决导入日期格式数据为数字问题

EasyExcel实现Converter接口解决导入日期格式数据为数字问题

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;
    }
}
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值