Excel中日期的导入导出,关联数据库时,实体类中的日期类型使用Date接收,导致时间精确到秒,使用@DateTimeFormat("yyyy-MM-dd")也会出现问题。
转载:使用easyExcel导入导出Date类型的转换问题_easyexcel 导入日期格式-CSDN博客
解决方案:
一、自定义转换器
public class DatetimeConverter implements Converter<Date> {
@Override
public Class<Date> supportJavaTypeKey() {
return Date.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
/**
* 这里读的时候会调用
*
* @param cellData excel数据 (NotNull)
* @param contentProperty excel属性 (Nullable)
* @param globalConfiguration 全局配置 (NotNull)
* @return 读取到内存中的数据
*/
@Override
public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
DateTimeFormat annotation = contentProperty.getField().getAnnotation(DateTimeFormat.class);
String format = Objects.nonNull(annotation) ? annotation.value() : "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
Date result = sdf.parse(cellData.getStringValue);
return result;
}
/**
* 写的时候会调用
*
* @param value java value (NotNull)
* @param contentProperty excel属性 (Nullable)
* @param globalConfiguration 全局配置 (NotNull)
* @return 写出到excel文件的数据
*/
@Override
public WriteCellData<Date> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
DateTimeFormat annotation = contentProperty.getField().getAnnotation(DateTimeFormat.class);
String format = Objects.nonNull(annotation) ? annotation.value() : "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
String result = sdf.format(value);
return new WriteCellData<>(result);
}
}
二、entity实体类对应的属性添加@ExcelProperty注解,在注解的converter属性中加入自定义的转换器类
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = "上传时间", converter = DatetimeConverter.class)
private Date dateTime;