首页 > 其他分享 >springboot集成easyexcel实现导入导出

springboot集成easyexcel实现导入导出

时间:2023-06-21 15:26:08浏览次数:34  
标签:springboot easyexcel ExcelProperty private 导入 article import com Schema

1、添加依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>

2、controller

   /**
     * 基于Listener方式从Excel导入会员列表
     */
    @Operation(summary = "导入垃圾厢房数据")
    @PostMapping(value = "/import")
    public Result importWasteRoom(@RequestPart("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), WasteRoomInfoExcelDTO.class, new WasteRoomInfoExcelListener(wasteRoomInfoService)).sheet().doRead();
        return Result.success();
    }
package com.zygh.hzhw.manage.dto;

import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @ExcelIgnore:忽略掉该字段;
 * @ExcelProperty("用户名"):设置该列的名称为”用户名“;
 * @ColumnWidth(20):设置表格列的宽度为20;
 * @DateTimeFormat("yyyy-MM-dd"):按照指定的格式对日期进行格式化;
 * @ExcelProperty(value = "性别", converter = GenderConverter.class):自定义内容转换器,类似枚举的实现,将“男”、“女”转换成“0”、“1”的数值。
 * 垃圾厢房信息
 * @author liubh
 */
@Data
//切记不能添加次注解,否则对象映射不上
//@Accessors(chain = true)
public class WasteRoomInfoExcelDTO implements Serializable {

    /**
     * 街道办事处
     */
    @ExcelProperty("街道办事处")
    @Schema(description = "街道办事处")
    private String street;

    /**
     * 社区
     */
    @ExcelProperty("社区")
    @Schema(description = "社区")
    private String community;

    /**
     * 小区
     */
    @ExcelProperty("小区")
    @Schema(description = "小区")
    private String village;

    /**
     * 位置
     */
    @ExcelProperty("位置")
    @Schema(description = "位置")
    private String locationName;

//    /**
//     * 类型
//     */
//    @Schema(description = "类型")
//    private Integer type;

    /**
     * 垃圾桶数量
     */
    @ExcelProperty("垃圾桶数量")
    @Schema(description = "垃圾桶数量")
    private Integer wasteNumber;


    /**
     * 回收柜数量
     */

    @ExcelProperty("回收柜数量")
    @Schema(description = "回收柜数量")
    private Integer recoveryNumber;

    /**
     * 垃圾箱编号
     */
    @ExcelProperty("垃圾箱编号")
    @Schema(description = "垃圾箱编号")
    private String wasteCode;

    /**
     * 大屏终端编号
     */
    @ExcelProperty("大屏终端编号")
    @Schema(description = "大屏终端编号")
    private String largeScreen;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;
}
package com.zygh.hzhw.manage.handler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.zygh.hzhw.manage.dto.WasteRoomInfoExcelDTO;
import com.zygh.hzhw.manage.entity.WasteRoomInfo;
import com.zygh.hzhw.manage.service.WasteRoomInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

/**
 * // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 *
 * @author liubh
 */
@Slf4j
public class WasteRoomInfoExcelListener extends AnalysisEventListener<WasteRoomInfoExcelDTO> {
    /**
     * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
     */

    private static final int BATCH_COUNT = 10;
    /**
     * 缓存的数据
     */
    private List<WasteRoomInfo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    public WasteRoomInfoService wasteRoomInfoService;

    public WasteRoomInfoExcelListener(WasteRoomInfoService wasteRoomInfoService) {
        this.wasteRoomInfoService = wasteRoomInfoService;
    }

    @Override
    public void invoke(WasteRoomInfoExcelDTO wasteRoomInfoExcelDTO, AnalysisContext analysisContext) {
        WasteRoomInfo wasteRoomInfo = new WasteRoomInfo();
        BeanUtils.copyProperties(wasteRoomInfoExcelDTO, wasteRoomInfo);
        cachedDataList.add(wasteRoomInfo);
        // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData(cachedDataList);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 保存数据
     *
     * @param wasteRoomInfoExcelDTOList
     */
    private void saveData(List<WasteRoomInfo> wasteRoomInfoExcelDTOList) {
        log.info("{}条数据,开始存储数据库!", cachedDataList.size());
        wasteRoomInfoService.saveBatch(wasteRoomInfoExcelDTOList);
        log.info("存储数据库成功!");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // do something
        System.out.println("读取Excel完毕");
        // do something
    }
}

欢迎关注公众号:

 

参考:https://developer.aliyun.com/article/1248377?spm=a2c6h.12873639.article-detail.28.37347e47pXAynm&scm=20140722.ID_community@@article@@1248377._.ID_community@@article@@1248377-OR_rec-V_1-RL_community@@article@@1057858

  https://developer.aliyun.com/article/1226862?spm=a2c6h.12873639.article-detail.31.37347e47pXAynm&scm=20140722.ID_community@@article@@1226862._.ID_community@@article@@1226862-OR_rec-V_1-RL_community@@article@@1057858

标签:springboot,easyexcel,ExcelProperty,private,导入,article,import,com,Schema
From: https://www.cnblogs.com/liubaihui/p/17496273.html

相关文章

  • springboot简单依赖
    <?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/......
  • springboot启动流程 (3) 自动装配
    在SpringBoot中,EnableAutoConfiguration注解用于开启自动装配功能。本文将详细分析该注解的工作流程。EnableAutoConfiguration注解启用SpringBoot自动装配功能,尝试猜测和配置可能需要的组件Bean。自动装配类通常是根据类路径和定义的Bean来应用的。例如,如果类路径上有tomcat-......
  • Postgresql 数据库导入导出 物理VS逻辑 集合
    PostgreSQL数据的导入导出本身并没有特别高的技术要求,属于日常操作,但熟悉导入导出以及选择数据导入导出的方式还是有点思考空间的。怎么导出数据的方式更稳妥,更适应业务的需求。下面就先总结数据导入导出中的数据导出的一部分方式和命令的实例,其中一些也是我在总结中发现的,例如COP......
  • Jenkins部署前后端不分离springboot项目
    背景写这篇博客的时候我还是大学生,学校期末课程设计时要求使用Jenkins部署项目,所以使用windows,但是企业中都是使用linux,往往还会搭建一个gitlab。下面我介绍的是在window环境下使用jenkins部署项目,这阵子搞这个期末作业时感觉收获还是挺大的,专门记录下。持续集成(CI)持续集成......
  • Springboot api的controller如何接口一个List<Object>参数
    1.正常情况下,你可能会这样写:@PostMapping("/delete")@ApiOperation("Deletelistdata")@ResponseStatus(HttpStatus.OK)@ResponseBodypublicDBUpdateStatusdeleteTestCaseDatas(List<TestCaseInfo>testCaseInfoList){......
  • Springboot 框架中的Entity,Dao,Service,Controller的关系
    SpringBoot框架中的Entity,DAO,Service,Controller层的关系参考:https://blog.csdn.net/weixin_44532671/article/details/117914161https://blog.csdn.net/m0_47552180/article/details/125613332......
  • SpringBoot之MVC配置(WebMvcConfigurer详解)
    一:基本介绍SpringMVC是一种常用的JavaWeb框架,它提供了一种基于MVC模式的开发方式,可以方便地实现Web应用程序。在SpringMVC中,WebMvcConfigurer是一种常用的配置方式,可以允许我们自定义SpringMVC的行为,比如添加拦截器、消息转换器等。在本文中,我们将介绍什么是WebMvcConfi......
  • Springboot03
    1.Springboot引入JSPspring官网说,不建议springboot使用jspspring默认值支持Thymeleaf、FreeMarker·、Velocity·、GroovyJSP1.1.引入jsp相关的依赖<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId>&l......
  • 【web开发】PHP命名空间的别名和导入
    前言前面两篇文章我们详细介绍了PHP命名空间的定义和基本使用以及命名空间相关术语解读,对PHP的命名空间的有了更多的了解,本文我们再深入探索PHP命名空间的更多使用技巧。废话不多说,直接上菜。命名空间的别名和导入涉及到命名空间的使用,命名空间中的别名和导入这俩个概念我们是无法......
  • 使用EasyExcel对excel数据进行相似度判断
    @DatapublicclassExeclDto{/***execl表*/privateStringfilename;/***需要匹配的工作表名*/privateStringname1;/***需要匹配的工作表名*/privateStringname2;} @SpringBootTest@Slf4j......