【日常记录】EasyExcel支持时间字符串同org.joda.time.DateTime转化

复制代码
Author:赵志乾
Date:2024-06-11
Declaration:All Right Reserved!!!

**问题:**默认情况下,EasyExcel不支持时间字符串到org.joda.time.DateTime的转化。报错信息如下:

复制代码
Exception in thread "main" com.alibaba.excel.exception.ExcelDataConvertException: Converter not found, convert STRING to org.joda.time.DateTime

**解决方案:**自定义Converter,代码如下:

复制代码
// step1: 自定义Converter
public class DateTimeConverter implements Converter<DateTime> {

    private static final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Class<DateTime> supportJavaTypeKey() {
        return DateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public DateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return DateTime.parse(cellData.getStringValue(), dateFormatter);
    }


    @Override
    public WriteCellData<String> convertToExcelData(DateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(value.toString(dateFormatter));
    }
}



// step2: 进行读写时注册自定义Converter
EasyExcel.read(readFile, clazz, new PageReadListener<T>(result::addAll, 100))
                .registerConverter(new DateTimeConverter())
                .sheet(sheetName)
                .doRead();
EasyExcel.write(writeFile , clazz)
                .registerConverter(new DateTimeConverter())
                .sheet(sheetName)
                .doWrite(result);
相关推荐
程序员清风17 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林55118 小时前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
华仔啊1 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing1 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide2 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家2 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺2 天前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602732 天前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端