在SpringBoot进行excel表格导出数据时提示:
com.alibaba.excel.exception.ExcelDataConvertException: Can not find 'Converter' support class LocalDateTime.
是因为默认为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日期格式属性上添加注解:
@ExcelProperty(value = "开始时间", converter = LocalDateStringConverter.class)
private LocalDateTime startTime;
3.在Controller中进行正常的导出调用即可
/**
* 导出项目信息
*/
@SneakyThrows
@GetMapping("export-project")
@ApiOperationSupport(order = 13)
@ApiOperation(value = "导出项目", notes = "传入项目")
public void exportProject(@ApiIgnore @RequestParam Map<String, Object> project,HttpServletResponse response) {
QueryWrapper<Project> queryWrapper = Condition.getQueryWrapper(project, Project.class);
queryWrapper.lambda().eq(Project::getIsDeleted, BladeConstant.DB_NOT_DELETED);
List<ProjectExcel> list = projectService.exportProject(queryWrapper);
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding(Charsets.UTF_8.name());
String fileName = URLEncoder.encode("项目数据导出", Charsets.UTF_8.name());
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), ProjectExcel.class).sheet("项目数据表").doWrite(list);
}