在使用easyexcel进行表格导出的时候出现错误:
com.alibaba.excel.exception.ExcelDataConvertException: Can not find ‘Converter’ support class LocalDate.
在springboot项目中使用使用easyexcel,默认是支持Date日期格式的导出的,但是不支持LocalDate日期格式所以需要用到自定义转换器
1.导入依赖
<!-- easyExcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
2.自定义转换器类
package com.mju.library.utils;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* 自定义LocalDateStringConverter
* 用于解决使用easyexcel导出表格时候,默认不支持LocalDateTime日期格式
*
* 在需要的属性上添加注解 @ExcelProperty(value = "创建日期", converter = LocalDateStringConverter.class)
*/
public class LocalDateStringConverter implements Converter<LocalDate> {
@Override
public Class supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public WriteCellData<?> convertToExcelData(LocalDate localDate, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
WriteCellData cellData = new WriteCellData();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd ");
String cellValue;
cellValue=formatter.format(localDate);
cellData.setType(CellDataTypeEnum.STRING);
cellData.setStringValue(cellValue);
cellData.setData(cellValue);
return cellData;
}
}
3.在对应的localDate日期格式添加注解:
//@DateTimeFormat("yyyy-MM-dd") //导入阿里巴巴的包,适用于date格式日期,自定义日期的格式
@ExcelProperty(value = "创建时间",converter = LocalDateStringConverter.class)
// @ExcelIgnore
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDate createtime;
4.启动服务
@GetMapping("/batchExport")
public void batchExport(HttpServletResponse response) throws IOException {
List<ReturnBook> list = returnBookService.findAll();
//代表的时Excel文件类型
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=returnBook.xlsx");
// 这里需要设置不关闭流
OutputStream outputStream = response.getOutputStream();
EasyExcel.write(outputStream)
.excelType(ExcelTypeEnum.XLSX)
//设置表面
.sheet("图书列表")
//实体类一一对应的列名
.head(ReturnBook.class)
.doWrite(list);
outputStream.flush();
outputStream.close();
}