如何解决EasyExcel导出文件LocalDateTime报错问题

 更新时间:2023年06月09日 09:43:30   作者:陈宝子  
这篇文章主要介绍了如何解决EasyExcel导出文件LocalDateTime报错问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

解决EasyExcel导出文件LocalDateTime报错

问题引出

我在参与一个项目的时候接触到数据表格导出为Excel表格的需求,但是在导出的时候会出现报错

Cannot find ‘Converter’ support class LocalDateTime

原因是我需要导出的实体类中存在 LocalDateTime 类型的属性,而又恰巧 EasyExcel 不支持 LocalDate 和 LocalDateTime 接收数据,啊人生

解决方案

在寻找了多篇文章之后,在下面对这个问题进行总结,既然默认不支持我使用这个类型,那就杀出一条路来。

首先先来看报的错误提示:

Cannot find ‘Converter’ support class LocalDateTime

明显可以看出来是找不到 LocalDateTime 的一个 Converter,那么这个所谓的 Converter 到底是个什么东西呢?既然他缺少这个东西我们能不能给他自己弄一个上去呢?说干就干!(其实解决方法也真就是这个)

自定义Converter

Converter 在这里其实是一个字段转换器,在 EasyExcel 中担任将Java属性转换成Excel表格中合法数据的一个小东西。

由于EasyExcel自己没有我们需要的 LocalDateTime 的字段转换器,那我们就自己搞一个出来。

在 config 包下新建一个自定义的字段转换器 LocalDateTimeConverter 。

package edu.lingnan.rili.converter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 * @author xBaozi
 * @version 1.0
 * @classname LocalDateTimeConverter
 * @description EasyExcel LocalDateTime转换器
 * @date 2022/3/19 2:17
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    @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(DEFAULT_PATTERN));
    }
    @Override
    public CellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new CellData<>(value.format(DateTimeFormatter.ofPattern(DEFAULT_PATTERN)));
    }
}

引用 LocalDateTimeConverter

既然这东西是本来没有然后我们自己弄出来的,那肯定要告诉程序:**诶!这里我给你生了个崽,要记得领回去啊!**所以,我们在原本需要导出的 LocalDateTime 类型中的 @ExcelProperty 注解中引入自定义的字段转换器。

同时要加上一个JsonFormat的格式化注解,将该属性转换成 json格式,这里要注意的就是要导入一下阿里巴巴的 fastjson Maven坐标了。

@ExcelProperty(value = "操作时间", index = 8, converter = LocalDateTimeConverter.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("操作时间")
private LocalDateTime operationTime;
<!-- fastjson的Maven坐标 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

好啦!到这里我们遇到的问题就已经解决了呀!虽然说前期刚遇到这个问题的时候一直在被折磨,但是却是一个很好的一个提升机会,没点儿bug,怎么能保得住头发呢是吧。

EasyExcel导出问题

报错信息!!!

错误一:

com.alibaba.excel.exception.ExcelAnalysisException: java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.beans.BeanMap$Generator

com.alibaba.excel.exception.ExcelAnalysisException: java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V

上面两种报错!!!都是一个原因,各种查询之后,说是版本冲突,这种就很头疼

经过排查,我在pom中将单元测试的依赖注解之后,导入就正常了

错误二:

com.alibaba.excel.exception.ExcelDataConvertException: Can not find 'Converter' support

原因:默认只能转换BigDecimal、Bolean、Byte[]、btye[]、Byte、Date、Double、File、Float、InputStream、Integer、Long、Short、URL几种类型,== 所以必须自己手动编写一个转换类==

我原本得实体类:用的数据类型是:LocalDateTime,不能自动转换

修改后:自己编辑了一个转换类LocalDateConverter

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @ExcelProperty(value="时间",index = 10,converter = LocalDateConverter.class)
    @ColumnWidth(25)
    private LocalDateTime turnoutTime;

LocalDateConverter

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateConverter 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 excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
    @Override
    public CellData convertToExcelData(LocalDateTime localDate, ExcelContentProperty excelContentProperty
            , GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData<>(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
}

一般情况下应该是解决了!!!

但是部署后问题还是一样!!也不知道为什么没有生效。

于是乎,经过不断得尝试,还是报一样得错,无奈之下我只能在:EasyExcel写入数据之前得到list集合循环遍历,然后逐个用字符串进行时间转换

实体类更改:用一个String字符来代替LocalDateTime 来写入Excel

代码

   @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @ExcelIgnore
//    @ExcelProperty(value="时间",index = 10,converter = LocalDateConverter.class)
    private LocalDateTime turnoutTime;
    @ExcelProperty(value="时间",index = 10)
    private String turnoutTimeString;

逻辑层更改

 List<Student> stus= (List<Student>) studentService.listByIds(student.getIds());
                log.info("stuss数据条数:{}",stus.size());
                List<Student> list = JSON.parseArray(JSON.toJSONString(stus), Student.class);
                for (Student stu: list) {
					//类型的判断
                    String sex="男";
                    if (stu.getSex() == 1) {
                        sex="男";
                    } else if (stu.getSex() == 2) {
                        sex="女";
                    }
                    stu.setSexName(sex);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
					//将LocalDateTime转换String
                    stu.setTurnoutTimeString(stu.getTurnoutTime().format(formatter));
                }
                excelWriter.write(list, sheet);
           		excelWriter.finish();

最后到这里再进行运行,就没什么问题了,只是可能有些性能的消耗,毕竟要是数据量大,10w+的数据,这种情况有待考量,至于转换类不生效的问题后期发现了再更吧,有知道的伙计们也分享一下呗!!(奇怪的是我在注解里面加得index = 10得序号和 @ColumnWidth(25)都没有生效,当然类型的转换类也没有生效!!!)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java使用substring()截取(提取)子字符串

    Java使用substring()截取(提取)子字符串

    这篇文章主要介绍了Java使用substring()截取(提取)子字符串,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Java中scheduleAtFixedRate的用法

    Java中scheduleAtFixedRate的用法

    如何正确使用Java中的scheduleAtFixedRate是一篇介绍Java中定时任务调度器的文章。它详细介绍了scheduleAtFixedRate方法的用法、参数及作用,并给出了一些实例以帮助读者更好地理解其使用。本文为Java开发人员提供了一些实用的技巧,帮助他们更好地管理和控制定时任务
    2023-04-04
  • 使用SpringBoot生成war包的流程步骤

    使用SpringBoot生成war包的流程步骤

    一般情况下,在SpringBoot项目开发完成进行服务器部署时,都是打成JAR包进行部署运行的,但是在有些情况下也需要将其打成War包使用Tomcat进行部署,本篇文章就简单介绍一下SpringBoot如何打成War包,需要的朋友可以参考下
    2024-10-10
  • SpringBoot集成Milvus实现数据增删改查功能

    SpringBoot集成Milvus实现数据增删改查功能

    milvus支持的语言比较多,支持python, Java, Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboot框架集成和调用Milvus数据库,这篇文章主要介绍了SpringBoot集成Milvus,实现数据增删改查,需要的朋友可以参考下
    2025-04-04
  • SpringBoot使用Sa-Token实现路径拦截和特定接口放行

    SpringBoot使用Sa-Token实现路径拦截和特定接口放行

    这篇文章主要介绍了SpringBoot使用Sa-Token实现路径拦截和特定接口放行,文中通过代码示例讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-06-06
  • JavaWeb实现显示mysql数据库数据

    JavaWeb实现显示mysql数据库数据

    MySQL是最流行的关系型数据库管理系统,在WEB应用方面MySQL是最好的。本文将利用JavaWeb实现显示mysql数据库数据功能,需要的可以参考一下
    2022-03-03
  • SpringBoot 集成 activiti的示例代码

    SpringBoot 集成 activiti的示例代码

    这篇文章主要介绍了SpringBoot 集成 activiti的示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • 永久解决 Intellij idea 报错:Error :java 不支持发行版本5的问题

    永久解决 Intellij idea 报错:Error :java 不支持发行版本5的问题

    这篇文章主要介绍了永久解决 Intellij idea 报错:Error :java 不支持发行版本5的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • Spring中@PropertySource和@Value注解详解

    Spring中@PropertySource和@Value注解详解

    这篇文章主要介绍了Spring中@PropertySource和@Value注解详解,@PropertySource注解可以方便和灵活的向Spring的环境容器(org.springframework.core.env.Environment Environment)中注入一些属性,这些属性可以在Bean中使用,需要的朋友可以参考下
    2023-11-11
  • Java设计模式之原型模式详细解读

    Java设计模式之原型模式详细解读

    这篇文章主要介绍了Java设计模式之原型模式详细解读,原型模式属于创建型设计模式,用于创建重复的对象,且同时又保证了性能,该设计模式的好处是将对象的创建与调用方分离,需要的朋友可以参考下
    2023-12-12

最新评论