【日常记录】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);
相关推荐
马剑威(威哥爱编程)3 分钟前
鸿蒙6开发视频播放器的屏幕方向适配问题
java·音视频·harmonyos
JIngJaneIL7 分钟前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
V***u45336 分钟前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿1 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
_大龄1 小时前
前端解析excel
前端·excel
i***t9191 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***08291 小时前
【监控】spring actuator源码速读
java·spring boot·spring
麦麦鸡腿堡1 小时前
Java_网络编程_InetAddress类与Socket类
java·服务器·网络
vx_dmxq2112 小时前
【PHP考研互助系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·spring boot·mysql·考研·微信小程序·小程序·php
5***g2982 小时前
新手如何快速搭建一个Springboot项目
java·spring boot·后端