首页 > 其他分享 >SpringBoot使用EasyExcel将Excel数据直接转换为类对象

SpringBoot使用EasyExcel将Excel数据直接转换为类对象

时间:2023-05-16 23:24:38浏览次数:50  
标签:return SpringBoot EasyExcel excel value 注释 param 为类 public

背景

相比于读取excel到List<List<String>>对象中,抽象一个方法将excel数据直接一步读取到指定的类对象中,更为方便。

代码

通过类Class读取excel数据到对象

/**
 * 使用Class来读取Excel
 *
 * @param inputStream   Excel的输入流
 * @param excelTypeEnum Excel的格式(XLS或XLSX)
 * @return 返回 ClassList 的列表
 */
public static <T> List<T> readExcelConvertObjectList(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Class<T> classT) {
    return readExcelWithClassList(inputStream, excelTypeEnum, 1, classT);
}
/**
 * 读取excel数据到数据对象
 *
 * @param inputStream 文件流
 * @param excelTypeEnum 文件类型Excel的格式(XLS或XLSX)
 * @param headLineNum 开始读取数据的行
 * @param classT 转为对象的CLASS
 * @param <T>
 * @return
 */
public static <T> List<T> readExcelConvertObjectList(InputStream inputStream, ExcelTypeEnum excelTypeEnum,
                                                 @Nullable Integer headLineNum, Class<T> classT) {
    if (headLineNum == null) {
        headLineNum = 1;
    }
    return EasyExcel.read(inputStream).excelType(excelTypeEnum)
            .registerConverter(new StringConverter())
            .head(classT)
            .sheet()
            .headRowNumber(headLineNum)
            .doReadSync();
}

StringConvert

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;
 
public class StringConverter implements Converter<String> {
 
    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
 
    /**
     * 将excel对象转成Java对象,这里读的时候会调用
     *
     * @param cellData            NotNull
     * @param contentProperty     Nullable
     * @param globalConfiguration NotNull
     * @return
     */
    @Override
    public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        return cellData.getStringValue();
    }
 
    /**
     * 将Java对象转成String对象,写出的时候调用
     *
     * @param value
     * @param contentProperty
     * @param globalConfiguration
     * @return
     */
    @Override
    public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {
        return new CellData(value);
    }
}

使用时创建对应Excel的Java对象

@Data
public class BankInfoImportExcelDto {
 
    @ExcelProperty(index = 0,value = "银行ID")
    @Min(value = 1 message = "ID不能小于1")
    private Long bankId;
 
    @ExcelProperty(index = 1,value = "银行名称")
    @NotBlank
    private String bankName;
 
    @ExcelProperty(index = 2,value = "银行地址")
    private String address;
 
}

编写Controller

@PostMapping("/import")
    public ResultT importExcel(@RequestParam("file") MultipartFile file) throws IOException {
      
        InputStream inputStream = file.getInputStream();
        List<BankInfoImportExcelDto> importBankInfoExcelDtoList = readExcelConvertObjectList(inputStream,ExcelTypeEnum.XLSX,BankInfoImportExcelDto.class);

......
    }

JSR303注解

JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Validation。HibernateValidator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

Bean Validation 中内置的 constraint

Constraint详细信息
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式

Hibernate Validator 附加的 constraint

Constraint详细信息
@Email 被注释的元素必须是电子邮箱地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range 被注释的元素必须在合适的范围内

 

相关文章:

https://www.dekux.com/post/32a50c31.html

https://cloud.tencent.com/developer/article/1888727

https://blog.csdn.net/qq_53121751/article/details/125301777

 

本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

首发链接:https://www.cnblogs.com/lingyejun/p/17398364.html

标签:return,SpringBoot,EasyExcel,excel,value,注释,param,为类,public
From: https://www.cnblogs.com/lingyejun/p/17398364.html

相关文章

  • SpringBoot整合knife4j
    ●knife4j是一个集Swagger2和PoenApi为一体的增强解决方案导入依赖<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency>编写相关配置类......
  • SpringBoot添加JSP支持
    ①创建一个新的MavenWeb项目,命名为SpringBoot_jsptest建成之后会如上图所示,报错是因为没有加入jsp的支持。②按照Maven规范,在src/main/下新建一个名为resource的文件夹,并在下面新建static以及templates文件夹修改pom.xml文件:      1、在url标签后面加入parent元素: <!--......
  • SpringBoot实现注册时头像上传与下载
    一、说明     1.为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。      2.SpringMVC为文件上传提供了直接的支持,这种支持是通过MultipartResolver实现的,SpringMVC使用ApacheCommonsFileUpload技术实现了MultipartResolver实现......
  • SpringBoot中使用Thymeleaf常用功能(一):表达式访问数据
    环境搭建:  创建一个Maven项目,按照Maven项目的规范,在src/main/下新建一个名为resources的文件夹,并在下面新建static和templates文件夹。 ① 修改pom.xml:<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi......
  • SpringBoot入门案例后的4个问题
    1.我们的工程在引入`spring-boot-starter-web`依赖的时候,为什么没有指定版本版本锁定 我们的项目继承了spring-boot-starter-parent父工程,它内部的父工程spring-boot-dependencies已经锁定了部分依赖的版本号,因此自己创建工程中无需再指定版本。2.`spring-......
  • SpringBoot+Prometheus+Grafana实现应用程序可视化监控
    1、SpringBoot应用暴露监控指标maven依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupI......
  • SpringBoot优化之项目启动优化
    目录1SpringBoot启动优化1.1背景1.2观察SpringBoot启动run方法1.2.1SpringApplicationRunListener接口1.2.2使用SpringApplicationRunListener监控1.3监控Bean注入耗时1.3.1BeanPostProcessor接口1.4优化方案1.4.1如何解决扫描路径过多1.4.2如何解决Bean初始......
  • springboot 整合webservice 相关说明
    1.环境依赖jdk8,springboot2.3.12.release,cxf版本需要根据springboot版本修改,方法:查看springboot版本的发布日期,然后根据日期找相近的两个版本<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><versi......
  • springboot(8)--定制服务
    springboot的服务配置除了application.properties,还可以通过implements WebServerFactoryCustomizer<T>定制服务,例如指定容器,端口,协议等等我们只要在继承类中添加自己的配置即可*@ClassnameTomcatServerConfiger*@CreatedbyMichael*@Date2023/5/15*@Descriptio......
  • SpringBoot发布https服务
    一、生成SSL证书 1、进入本地jdk的路径cdD:\Program\jdk1.8.0_77\jre\lib\securitycmd窗口生成证书HSoftTiger.keystore到D盘keytool-genkey-aliastigerCompany-keyalgRSA-keysize1024-keypasstigerpass-validity3650-keystoreD:\HSoftTiger.keystore-storep......