java使用EasyExcel生成表格
一、调用方法
public static <E> void exportList(HttpServletResponse response, String fileName,String sheetName,List<E> list, Class<E> tClass) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "." + "xls");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
EasyExcel.write(response.getOutputStream(), tClass).excelType(ExcelTypeEnum.XLS)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(StringUtils.isNotBlank(sheetName) ? sheetName :"Sheet1").doWrite(list);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
二、在主要的实体类属性上添加注解
@ExcelProperty(value = "姓名", index = 0)
@@ColumnWidth(value = 30)
三、关于实体类属性类型为LocalDateTime转换(注意EasyExcel是支持Date类型的)
报错:
Can not find 'Converter' support class LocalDateTime.
解决:编写一个转换类,并作用于类对应属性上
@ExcelProperty(value = "发送时间",index = 5,converter = LocalDateTimeConverter.class)
@ColumnWidth(value = 20)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
@Override
public Class<LocalDateTime> supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
@Override
public CellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}