SpringCloud微服务实战——搭建企业级开发框架(三十):整合EasyExcel实现数据表格导入导出功能

本文涉及的产品
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
云原生网关 MSE Higress,422元/月
简介: 批量上传数据导入、数据统计分析导出,已经基本是系统必不可缺的一项功能,这里从性能和易用性方面考虑,集成EasyExcel。EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目,在尽可能节约内存的情况下支持读写百M的Excel:  Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,

批量上传数据导入、数据统计分析导出,已经基本是系统必不可缺的一项功能,这里从性能和易用性方面考虑,集成EasyExcel。EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目,在尽可能节约内存的情况下支持读写百M的Excel:


  Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便。(https://github.com/alibaba/easyexcel/)


一、引入依赖的库


1、在GitEgg-Platform项目中修改gitegg-platform-bom工程的pom.xml文件,增加EasyExcel的Maven依赖。


<properties>
        ......
        <!-- Excel 数据导入导出 -->
        <easyexcel.version>2.2.10</easyexcel.version>
    </properties>
   <dependencyManagement>
        <dependencies>
           ......
            <!-- Excel 数据导入导出 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>${easyexcel.version}</version>
            </dependency>
            ......
        </dependencies>
    </dependencyManagement>


2、修改gitegg-platform-boot工程的pom.xml文件,添加EasyExcel依赖。这里考虑到数据导入导出是系统必备功能,所有引用springboot工程的微服务都需要用到EasyExcel,并且目前版本EasyExcel不支持LocalDateTime日期格式,这里需要自定义LocalDateTimeConverter转换器,用于在数据导入导出时支持LocalDateTime。


pom.xml文件


<dependencies>
        ......
        <!-- Excel 数据导入导出 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
        </dependency>
    </dependencies>


自定义LocalDateTime转换器LocalDateTimeConverter.java


package com.gitegg.platform.boot.excel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import com.alibaba.excel.annotation.format.DateTimeFormat;
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;
/**
 * 自定义LocalDateStringConverter
 * 用于解决使用easyexcel导出表格时候,默认不支持LocalDateTime日期格式
 *
 * @author GitEgg
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
    /**
     * 不使用{@code @DateTimeFormat}注解指定日期格式时,默认会使用该格式.
     */
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
    /**
     * 这里读的时候会调用
     *
     * @param cellData            excel数据 (NotNull)
     * @param contentProperty     excel属性 (Nullable)
     * @param globalConfiguration 全局配置 (NotNull)
     * @return 读取到内存中的数据
     */
    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        DateTimeFormat annotation = contentProperty.getField().getAnnotation(DateTimeFormat.class);
        return LocalDateTime.parse(cellData.getStringValue(),
                DateTimeFormatter.ofPattern(Objects.nonNull(annotation) ? annotation.value() : DEFAULT_PATTERN));
    }
    /**
     * 写的时候会调用
     *
     * @param value               java value (NotNull)
     * @param contentProperty     excel属性 (Nullable)
     * @param globalConfiguration 全局配置 (NotNull)
     * @return 写出到excel文件的数据
     */
    @Override
    public CellData convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        DateTimeFormat annotation = contentProperty.getField().getAnnotation(DateTimeFormat.class);
        return new CellData(value.format(DateTimeFormatter.ofPattern(Objects.nonNull(annotation) ? annotation.value() : DEFAULT_PATTERN)));
    }
}


  以上依赖及转换器编辑好之后,点击Platform的install,将依赖重新安装到本地库,然后GitEgg-Cloud就可以使用定义的依赖和转换器了。


二、业务实现及测试


  因为依赖的库及转换器都是放到gitegg-platform-boot工程下的,所以,所有使用到gitegg-platform-boot的都可以直接使用EasyExcel的相关功能,在GitEgg-Cloud项目下重新Reload All Maven Projects。这里以gitegg-code-generator微服务项目举例说明数据导入导出的用法。


1、EasyExcel可以根据实体类的注解来进行Excel的读取和生成,在entity目录下新建数据导入和导出的实体类模板文件。


文件导入的实体类模板DatasourceImport.java


package com.gitegg.code.generator.datasource.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
 * <p>
 * 数据源配置上传
 * </p>
 *
 * @author GitEgg
 * @since 2021-08-18 16:39:49
 */
@Data
@HeadRowHeight(20)
@ContentRowHeight(15)
@ApiModel(value="DatasourceImport对象", description="数据源配置导入")
public class DatasourceImport {
    @ApiModelProperty(value = "数据源名称")
    @ExcelProperty(value = "数据源名称" ,index = 0)
    @ColumnWidth(20)
    private String datasourceName;
    @ApiModelProperty(value = "连接地址")
    @ExcelProperty(value = "连接地址" ,index = 1)
    @ColumnWidth(20)
    private String url;
    @ApiModelProperty(value = "用户名")
    @ExcelProperty(value = "用户名" ,index = 2)
    @ColumnWidth(20)
    private String username;
    @ApiModelProperty(value = "密码")
    @ExcelProperty(value = "密码" ,index = 3)
    @ColumnWidth(20)
    private String password;
    @ApiModelProperty(value = "数据库驱动")
    @ExcelProperty(value = "数据库驱动" ,index = 4)
    @ColumnWidth(20)
    private String driver;
    @ApiModelProperty(value = "数据库类型")
    @ExcelProperty(value = "数据库类型" ,index = 5)
    @ColumnWidth(20)
    private String dbType;
    @ApiModelProperty(value = "备注")
    @ExcelProperty(value = "备注" ,index = 6)
    @ColumnWidth(20)
    private String comments;
}


文件导出的实体类模板DatasourceExport.java


package com.gitegg.code.generator.datasource.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.gitegg.platform.boot.excel.LocalDateTimeConverter;
import lombok.Data;
import java.time.LocalDateTime;
/**
 * <p>
 * 数据源配置下载
 * </p>
 *
 * @author GitEgg
 * @since 2021-08-18 16:39:49
 */
@Data
@HeadRowHeight(20)
@ContentRowHeight(15)
@ApiModel(value="DatasourceExport对象", description="数据源配置导出")
public class DatasourceExport {
    @ApiModelProperty(value = "主键")
    @ExcelProperty(value = "序号" ,index = 0)
    @ColumnWidth(15)
    private Long id;
    @ApiModelProperty(value = "数据源名称")
    @ExcelProperty(value = "数据源名称" ,index = 1)
    @ColumnWidth(20)
    private String datasourceName;
    @ApiModelProperty(value = "连接地址")
    @ExcelProperty(value = "连接地址" ,index = 2)
    @ColumnWidth(20)
    private String url;
    @ApiModelProperty(value = "用户名")
    @ExcelProperty(value = "用户名" ,index = 3)
    @ColumnWidth(20)
    private String username;
    @ApiModelProperty(value = "密码")
    @ExcelProperty(value = "密码" ,index = 4)
    @ColumnWidth(20)
    private String password;
    @ApiModelProperty(value = "数据库驱动")
    @ExcelProperty(value = "数据库驱动" ,index = 5)
    @ColumnWidth(20)
    private String driver;
    @ApiModelProperty(value = "数据库类型")
    @ExcelProperty(value = "数据库类型" ,index = 6)
    @ColumnWidth(20)
    private String dbType;
    @ApiModelProperty(value = "备注")
    @ExcelProperty(value = "备注" ,index = 7)
    @ColumnWidth(20)
    private String comments;
    @ApiModelProperty(value = "创建日期")
    @ExcelProperty(value = "创建日期" ,index = 8, converter = LocalDateTimeConverter.class)
    @ColumnWidth(22)
    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;
}


2、在DatasourceController中新建上传和下载方法:


/**
     * 批量导出数据
     * @param response
     * @param queryDatasourceDTO
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, QueryDatasourceDTO queryDatasourceDTO) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据源列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<DatasourceDTO> dataSourceList = datasourceService.queryDatasourceList(queryDatasourceDTO);
        List<DatasourceExport> dataSourceExportList = new ArrayList<>();
        for (DatasourceDTO datasourceDTO : dataSourceList) {
            DatasourceExport dataSourceExport = BeanCopierUtils.copyByClass(datasourceDTO, DatasourceExport.class);
            dataSourceExportList.add(dataSourceExport);
        }
        String sheetName = "数据源列表";
        EasyExcel.write(response.getOutputStream(), DatasourceExport.class).sheet(sheetName).doWrite(dataSourceExportList);
    }
    /**
     * 下载导入模板
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据源导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        String sheetName = "数据源列表";
        EasyExcel.write(response.getOutputStream(), DatasourceImport.class).sheet(sheetName).doWrite(null);
    }
    /**
     * 上传数据
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result<?> upload(@RequestParam("uploadFile") MultipartFile file) throws IOException {
        List<DatasourceImport> datasourceImportList =  EasyExcel.read(file.getInputStream(), DatasourceImport.class, null).sheet().doReadSync();
        if (!CollectionUtils.isEmpty(datasourceImportList))
        {
            List<Datasource> datasourceList = new ArrayList<>();
            datasourceImportList.stream().forEach(datasourceImport-> {
                datasourceList.add(BeanCopierUtils.copyByClass(datasourceImport, Datasource.class));
            });
            datasourceService.saveBatch(datasourceList);
        }
        return Result.success();
    }


3、前端导出(下载)设置,我们前端框架请求用的是axios,正常情况下,普通的请求成功或失败返回的responseType为json格式,当我们下载文件时,请求返回的是文件流,这里需要设置下载请求的responseType为blob。考虑到下载是一个通用的功能,这里提取出下载方法为一个公共方法:首先是判断服务端的返回格式,当一个下载请求返回的是json格式时,那么说明这个请求失败,需要处理错误新题并提示,如果不是,那么走正常的文件流下载流程。


api请求


//请求的responseType设置为blob格式
export function downloadDatasourceList (query) {
  return request({
    url: '/gitegg-plugin-code/code/generator/datasource/download',
    method: 'get',
    responseType: 'blob',
    params: query
  })
}


导出/下载的公共方法


// 处理请求返回信息
export function handleDownloadBlod (fileName, response) {
    const res = response.data
    if (res.type === 'application/json') {
      const reader = new FileReader()
      reader.readAsText(response.data, 'utf-8')
      reader.onload = function () {
        const { msg } = JSON.parse(reader.result)
        notification.error({
          message: '下载失败',
          description: msg
        })
    }
  } else {
    exportBlod(fileName, res)
  }
}
// 导出Excel
export function exportBlod (fileName, data) {
  const blob = new Blob([data])
  const elink = document.createElement('a')
  elink.download = fileName
  elink.style.display = 'none'
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href)
  document.body.removeChild(elink)
}


vue页面调用


handleDownload () {
     this.downloadLoading = true
     downloadDatasourceList(this.listQuery).then(response => {
       handleDownloadBlod('数据源配置列表.xlsx', response)
       this.listLoading = false
     })
 },


4、前端导入(上传的设置),前端无论是Ant Design of Vue框架还是ElementUI框架都提供了上传组件,用法都是一样的,在上传之前需要组装FormData数据,除了上传的文件,还可以自定义传到后台的参数。


上传组件


<a-upload
        name="uploadFile"
        :show-upload-list="false"
        :before-upload="beforeUpload"
      >
        <a-button> <a-icon type="upload" /> 导入 </a-button>
      </a-upload>


上传方法


beforeUpload (file) {
     this.handleUpload(file)
     return false
 },
 handleUpload (file) {
     this.uploadedFileName = ''
     const formData = new FormData()
     formData.append('uploadFile', file)
     this.uploading = true
     uploadDatasource(formData).then(() => {
         this.uploading = false
         this.$message.success('数据导入成功')
         this.handleFilter()
     }).catch(err => {
       console.log('uploading', err)
       this.$message.error('数据导入失败')
     })
 },


  以上步骤,就把EasyExcel整合完成,基本的数据导入导出功能已经实现,在业务开发过程中,可能会用到复杂的Excel导出,比如包含图片、图表等的Excel导出,这一块需要根据具体业务需要,参考EasyExcel的详细用法来定制自己的导出方法。

相关文章
|
3月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
522 3
|
30天前
|
Cloud Native Serverless API
微服务架构实战指南:从单体应用到云原生的蜕变之路
🌟蒋星熠Jaxonic,代码为舟的星际旅人。深耕微服务架构,擅以DDD拆分服务、构建高可用通信与治理体系。分享从单体到云原生的实战经验,探索技术演进的无限可能。
微服务架构实战指南:从单体应用到云原生的蜕变之路
|
30天前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
Spring Boot 3.x 微服务架构实战指南
|
3月前
|
负载均衡 监控 Java
微服务稳定性三板斧:熔断、限流与负载均衡全面解析(附 Hystrix-Go 实战代码)
在微服务架构中,高可用与稳定性至关重要。本文详解熔断、限流与负载均衡三大关键技术,结合API网关与Hystrix-Go实战,帮助构建健壮、弹性的微服务系统。
352 1
微服务稳定性三板斧:熔断、限流与负载均衡全面解析(附 Hystrix-Go 实战代码)
|
8月前
|
NoSQL MongoDB 微服务
微服务——MongoDB实战演练——文章评论的基本增删改查
本节介绍了文章评论的基本增删改查功能实现。首先,在`cn.itcast.article.dao`包下创建数据访问接口`CommentRepository`,继承`MongoRepository`以支持MongoDB操作。接着,在`cn.itcast.article.service`包下创建业务逻辑类`CommentService`,通过注入`CommentRepository`实现保存、更新、删除及查询评论的功能。最后,新建Junit测试类`CommentServiceTest`,对保存和查询功能进行测试,并展示测试结果截图,验证功能的正确性。
141 2
|
8月前
|
NoSQL 测试技术 MongoDB
微服务——MongoDB实战演练——MongoTemplate实现评论点赞
本节介绍如何使用MongoTemplate实现评论点赞功能。传统方法通过查询整个文档并更新所有字段,效率较低。为优化性能,采用MongoTemplate对特定字段直接操作。代码中展示了如何利用`Query`和`Update`对象构建更新逻辑,通过`update.inc(&quot;likenum&quot;)`实现点赞数递增。测试用例验证了功能的正确性,确保点赞数成功加1。
162 0
|
8月前
|
NoSQL 测试技术 MongoDB
微服务——MongoDB实战演练——根据上级ID查询文章评论的分页列表
本节介绍如何根据上级ID查询文章评论的分页列表,主要包括以下内容:(1)在CommentRepository中新增`findByParentid`方法,用于按父ID查询子评论分页列表;(2)在CommentService中新增`findCommentListPageByParentid`方法,封装分页逻辑;(3)提供JUnit测试用例,验证功能正确性;(4)使用Compass插入测试数据并执行测试,展示查询结果。通过这些步骤,实现对评论的高效分页查询。
119 0
|
4月前
|
存储 负载均衡 Java
SpringCloud框架
本文介绍了微服务架构中常用的技术组件与原理,包括Nacos与Eureka的服务注册与发现机制、Nacos的分级存储模型、OpenFeign的远程调用流程、Ribbon与Spring LoadBalancer的负载均衡策略、Hystrix与Sentinel的限流熔断机制、滑动窗口算法原理,以及Spring Cloud Gateway的路由断言与过滤器功能,全面覆盖微服务核心治理能力。
|
5月前
|
NoSQL Java 微服务
2025 年最新 Java 面试从基础到微服务实战指南全解析
《Java面试实战指南:高并发与微服务架构解析》 本文针对Java开发者提供2025版面试技术要点,涵盖高并发电商系统设计、微服务架构实现及性能优化方案。核心内容包括:1)基于Spring Cloud和云原生技术的系统架构设计;2)JWT认证、Seata分布式事务等核心模块代码实现;3)数据库查询优化与高并发处理方案,响应时间从500ms优化至80ms;4)微服务调用可靠性保障方案。文章通过实战案例展现Java最新技术栈(Java 17/Spring Boot 3.2)的应用.
319 9
|
5月前
|
缓存 负载均衡 监控
微服务架构下的电商API接口设计:策略、方法与实战案例
本文探讨了微服务架构下的电商API接口设计,旨在打造高效、灵活与可扩展的电商系统。通过服务拆分(如商品、订单、支付等模块)和标准化设计(RESTful或GraphQL风格),确保接口一致性与易用性。同时,采用缓存策略、负载均衡及限流技术优化性能,并借助Prometheus等工具实现监控与日志管理。微服务架构的优势在于支持敏捷开发、高并发处理和独立部署,满足电商业务快速迭代需求。未来,电商API设计将向智能化与安全化方向发展。

热门文章

最新文章

下一篇
开通oss服务