【日常记录】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);
相关推荐
jack_xu1 小时前
经典大厂面试题——缓存穿透、缓存击穿、缓存雪崩
java·redis·后端
CHQIUU2 小时前
Java 设计模式心法之第4篇 - 单例 (Singleton) 的正确打开方式与避坑指南
java·单例模式·设计模式
碎梦归途2 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
神奇侠20242 小时前
基于PaddleOCR对图片中的excel进行识别并转换成word(一)
python·word·excel·paddleocr
lozhyf2 小时前
Eureka搭建
java·spring cloud
幽络源小助理3 小时前
SpringBoot民宿管理系统开发实现
java·spring boot·springboot·民宿系统
东阳马生架构3 小时前
Nacos简介—1.Nacos使用简介
java
爱发飙的蜗牛3 小时前
springboot--web开发请求参数接收注解
java·spring boot·后端
码熔burning3 小时前
【MQ篇】RabbitMQ之工作队列模式!
java·分布式·rabbitmq·mq
优雅的落幕3 小时前
Spring--统一数据返回格式与统一异常处理
java·spring·状态模式