1 Maven依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.8</version></dependency>
2 LocalDateConverter
LocalDate类型转换器。
package com.convert;import com.alibaba.excel.converters.Converter;import com.alibaba.excel.enums.CellDataTypeEnum;import com.alibaba.excel.metadata.*;import com.alibaba.excel.metadata.property.ExcelContentProperty;import org.ponent;import java.time.LocalDate;import java.time.format.DateTimeFormatter;/*** LocalDate类型转换器*/@Componentpublic class LocalDateConverter implements Converter<LocalDate> {@Overridepublic Class<LocalDate> supportJavaTypeKey() {return LocalDate.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}@Overridepublic LocalDate convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));}@Overridepublic CellData convertToExcelData(LocalDate localDate, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {return new CellData<>(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));}}
3 调试代码
/*** 调试自定义Convert** @param response*/@GetMapping("/customConvert")public void customConvert(HttpServletResponse response) throws IOException {List<List<Object>> sheetDataList = new ArrayList<>();List<Object> rowList = new ArrayList<>();rowList.add(LocalDate.parse("-07-30", DateTimeFormatter.ofPattern("yyyy-MM-dd")));sheetDataList.add(rowList);response.addHeader("Content-Disposition", "filename=test.xlsx" );//设置类型,扩展名为.xlsresponse.setContentType("application/vnd.ms-excel");ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())//加载类型转换器.registerConverter(new LocalDateConverter()).build();WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();excelWriter.write(sheetDataList, writeSheet);//千万别忘记finish 会帮忙关闭流excelWriter.finish();}
4 调试结果
旭东怪的个人空间-旭东怪个人主页-哔哩哔哩视频哔哩哔哩旭东怪的个人空间,提供旭东怪分享的视频、音频、文章、动态、收藏等内容,关注旭东怪账号,第一时间了解UP注动态。人生低谷不可怕,可怕的是坚持不到人生转折点的那一天/484264966?spm_id_from=333.1007.0.0