【日常记录】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);
相关推荐
TsengOnce8 小时前
Docker 安装达梦8数据库-5步成功
java·数据库
树码小子9 小时前
Spring框架:Spring程序快速上手
java·后端·spring
李松桃9 小时前
python第三次作业
java·前端·python
马士兵教育9 小时前
计算机专业学生入行IT行业,编程语言如何选择?
java·开发语言·c++·人工智能·python
本妖精不是妖精9 小时前
搭建 JNI 开发环境:使用 IntelliJ IDEA 和 CLion
java
老毛肚9 小时前
uniapp-ruoyi-spring部署宝塔
java·spring·uni-app
砚边数影9 小时前
决策树实战:基于 KingbaseES 的鸢尾花分类 —— 模型可视化输出
java·数据库·决策树·机器学习·分类·金仓数据库
夕除9 小时前
js--6
java·开发语言
手握风云-9 小时前
JavaEE 进阶第十三期:Spring Ioc & DI,从会用容器到成为容器(下)
java·spring·java-ee
组合缺一9 小时前
论 AI Skills 分布式发展的必然性:从单体智能到“云端大脑”的跃迁
java·人工智能·分布式·llm·mcp·skills