【日常记录】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);
相关推荐
非 白29 分钟前
【Java】单例模式
java·笔记·单例模式
IDRSolutions_CN42 分钟前
如何在 PDF 文件中嵌入自定义数据
java·经验分享·pdf·软件工程·团队开发
_风中无我。1 小时前
Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。
java·spring·json
bing_1581 小时前
Spring Boot 中为什么 需要限流、降级和熔断?
java
ccm031 小时前
高效开发助手:深入了解Hutool工具库
java·g工具库
雪落南城1 小时前
【Maven】maven加载不到包
java·maven
tekin4 小时前
Go、Java、Python、C/C++、PHP、Rust 语言全方位对比分析
java·c++·golang·编程语言对比·python 语言·php 语言·编程适用场景
李长渊哦5 小时前
Java 虚拟机(JVM)方法区详解
java·开发语言·jvm
陌殇殇6 小时前
002 SpringCloudAlibaba整合 - Feign远程调用、Loadbalancer负载均衡
java·spring cloud·微服务
猎人everest6 小时前
SpringBoot应用开发入门
java·spring boot·后端