EasyExcel-easyexcel进行excel数据导入导出,并解决JDK8的LocalDate报错Can not find ‘Converter‘ support class LocalDate

直接上代码

1.导入依赖,定义实体类

实体类字段上要加上@ExcelProperty(value = "xxx", index = 0)注解

<!--阿里巴巴Easyexcel-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>easyexcel</artifactId>
  <version>2.1.6</version>
</dependency>
@Data
@SuperBuilder
@NoArgsConstructor
@ApiModel(description = "Excel字段")
public class PlanExcelParam {
    @ExcelProperty(value = "序号", index = 0)
    @ApiModelProperty(value = "序号", dataType = "int")
    private int seq;

    @ExcelProperty(value = "名称", index = 1)
    @ApiModelProperty(value = "名称", dataType = "String")
    private String name;

    @ExcelProperty(value = "概要", index = 2)
    @ApiModelProperty(value = "概要", dataType = "String")
    private String summary;

    @ExcelProperty(value = "类型", index = 3)
    @ApiModelProperty(value = "类型", dataType = "String")
    private String types;

    @ExcelProperty(value = "部门", index = 4)
    @ApiModelProperty(value = "部门", dataType = "String")
    private String department;

    @ExcelProperty(value = "完成时间", index = 6)
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @ApiModelProperty(value = "完成时间", dataType = "LocalDate", example = "2020-12-07")
    private LocalDate finish_date_plan;

    @ExcelProperty(value = "状态", index = 9)
    @ApiModelProperty(value = "状态", dataType = "String")
    private String status;
}

2.编写工具类,针对这样的方法,一定是优先封装成工具类放到Common包,这样以后在任何模块需要生成excel都可以直接传参使用

public class ExcelUtils {

    /**
     * 导出excel核心方法
     *
     * @param
     */
    public static void export(HttpServletResponse response, Class head, List data, String sheetName, HorizontalCellStyleStrategy horizontalCellStyleStrategy) throws IOException {
        //给定导出实体类
        EasyExcel.write(response.getOutputStream(), head)
            //给定工作表名称
            .sheet(sheetName)
            //给定样式
            .registerWriteHandler(horizontalCellStyleStrategy)
            //给定导出数据
            .doWrite(data);
    }

    /**
     * 设置请求头、文件名
     *
     * @param fileName excel文件名
     */
    public static void setResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        //编码设置成UTF-8,excel文件格式为.xlsx
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 和easyexcel本身没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
    }

    /**
     * 设置生成excel样式 去除默认表头样式及设置内容居中,如有必要可重载该方法给定参数配置不同样式
     *
     * @return HorizontalCellStyleStrategy
     */
    public static HorizontalCellStyleStrategy getStyleStrategy() {
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //头策略使用默认
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }
}

3.编写service,调用ExcelUtils传入参数即可导出excel

这里省略Controller的代码,省略获取List data的代码,因为对这个功能的实现没啥意义

/**
 * 导出计划数据到excel
 *
 * @param response 响应信息
 */
@Override
public void exportExcel(HttpServletResponse response) throws IOException {
    //设置响应头和编码
    ExcelUtils.setResponse(response, "xxxx");
    //给定导出类,导出数据,工作表名称,样式
    ExcelUtils.export(response, PlanExcelParam.class, this.getAllPlanForExcel(), "xxxx", ExcelUtils.getStyleStrategy());
}

4.针对JDK8的LocalDate类型,easyexcel默认的类型转换器是无法处理的,要自行编写转换器

@Component
public class LocalDateConverter implements Converter<LocalDate> {

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {
        return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    @Override
    public CellData<String> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }

}

定义好类型转换器以后,有两种方式调用它

方式一:给ExcelWriterBuilders传入类型转换器

EasyExcel.write(response.getOutputStream(), PlanExcelParam.class).sheet("xxxx").registerConverter(new LocalDateConverter())...

方式二:定义全局类加载器,逻辑上,会先判断有没有针对需要转换的字段配置指定的转换器@ExcelProperty(converter = xxxxConverter.class)

关于如何配置全局加载器,参考EasyExcel自定义Converter全局加载器以及加载Converter的个人总结_excelproperty converter-CSDN博客

关于easyExcel导入和上传excel模板,参考easyExcel官网文档即可

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值