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);