本文主要是介绍【日常记录】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");@Overridepublic Class<DateTime> supportJavaTypeKey() {return DateTime.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}@Overridepublic DateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {return DateTime.parse(cellData.getStringValue(), dateFormatter);}@Overridepublic 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);
这篇关于【日常记录】EasyExcel支持时间字符串同org.joda.time.DateTime转化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!