在使用easyexcel进行表格导出的时候出现错误:
com.alibaba.excel.exception.ExcelDataConvertException: Can not find 'Converter' support class LocalDateTime.
在springboot项目中使用使用easyexcel,默认是支持Date日期格式的导出的,但是不支持LocalDateTime日期格式:
解决方案:
1、这时候需要自定义一个LocalDateStringConverter
/**
* 自定义LocalDateStringConverter
* 用于解决使用easyexcel导出表格时候,默认不支持LocalDateTime日期格式
*
* 在需要的属性上添加注解 @ExcelProperty(value = "入职时间", converter = LocalDateStringConverter.class)
*/
public class LocalDateStringConverter implements Converter<LocalDateTime> {
@Override
public Class supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
@Override
public CellData convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = formatter.format(localDateTime);
return new CellData(format);
}
}
2、在对应的localDateTime日期格式添加注解:
//@DateTimeFormat("yyyy-MM-dd") //导入阿里巴巴的包,适用于date格式日期,自定义日期的格式
@ExcelProperty(value = "入职时间", converter = LocalDateStringConverter.class)
private LocalDateTime createTime;
3、在controller中调用,以文件下载的形式进行表格的导出
@GetMapping("export")
public ResponseEntity<byte[]> exportAdminInfo() throws UnsupportedEncodingException {
List<Admin> list = adminService.findAll();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
EasyExcel.write(outputStream, Admin.class).sheet("员工信息表").doWrite(list);
byte[] bytes = outputStream.toByteArray();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDispositionFormData("attachement", URLEncoder.encode("员工信息表.xlsx", "utf-8"));
return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
}