百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

「SpringCloud」(三十)整合EasyExcel实现数据表格导入导出功能

ztj100 2024-11-05 13:27 13 浏览 0 评论

批量上传数据导入、数据统计分析导出,已经基本是系统必不可缺的一项功能,这里从性能和易用性方面考虑,集成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模式,在上层做了模型转换的封装,让使用者更加简单方便。

一、引入依赖的库

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的详细用法来定制自己的导出方法。

相关推荐

Vue 技术栈(全家桶)(vue technology)

Vue技术栈(全家桶)尚硅谷前端研究院第1章:Vue核心Vue简介官网英文官网:https://vuejs.org/中文官网:https://cn.vuejs.org/...

vue 基础- nextTick 的使用场景(vue的nexttick这个方法有什么用)

前言《vue基础》系列是再次回炉vue记的笔记,除了官网那部分知识点外,还会加入自己的一些理解。(里面会有部分和官网相同的文案,有经验的同学择感兴趣的阅读)在开发时,是不是遇到过这样的场景,响应...

vue3 组件初始化流程(vue组件初始化顺序)

学习完成响应式系统后,咋们来看看vue3组件的初始化流程既然是看vue组件的初始化流程,咋们先来创建基本的代码,跑跑流程(在app.vue中写入以下内容,来跑流程)...

vue3优雅的设置element-plus的table自动滚动到底部

场景我是需要在table最后添加一行数据,然后把滚动条滚动到最后。查网上的解决方案都是读取html结构,暴力的去获取,虽能解决问题,但是不喜欢这种打补丁的解决方案,我想着官方应该有相关的定义,于是就去...

Vue3为什么推荐使用ref而不是reactive

为什么推荐使用ref而不是reactivereactive本身具有很大局限性导致使用过程需要额外注意,如果忽视这些问题将对开发造成不小的麻烦;ref更像是vue2时代optionapi的data的替...

9、echarts 在 vue 中怎么引用?(必会)

首先我们初始化一个vue项目,执行vueinitwebpackechart,接着我们进入初始化的项目下。安装echarts,npminstallecharts-S//或...

无所不能,将 Vue 渲染到嵌入式液晶屏

该文章转载自公众号@前端时刻,https://mp.weixin.qq.com/s/WDHW36zhfNFVFVv4jO2vrA前言...

vue-element-admin 增删改查(五)(vue-element-admin怎么用)

此篇幅比较长,涉及到的小知识点也比较多,一定要耐心看完,记住学东西没有耐心可不行!!!一、添加和修改注:添加和编辑用到了同一个组件,也就是此篇文章你能学会如何封装组件及引用组件;第二能学会async和...

最全的 Vue 面试题+详解答案(vue面试题知识点大全)

前言本文整理了...

基于 vue3.0 桌面端朋友圈/登录验证+60s倒计时

今天给大家分享的是Vue3聊天实例中的朋友圈的实现及登录验证和倒计时操作。先上效果图这个是最新开发的vue3.x网页端聊天项目中的朋友圈模块。用到了ElementPlus...

不来看看这些 VUE 的生命周期钩子函数?| 原力计划

作者|huangfuyk责编|王晓曼出品|CSDN博客VUE的生命周期钩子函数:就是指在一个组件从创建到销毁的过程自动执行的函数,包含组件的变化。可以分为:创建、挂载、更新、销毁四个模块...

Vue3.5正式上线,父传子props用法更丝滑简洁

前言Vue3.5在2024-09-03正式上线,目前在Vue官网显最新版本已经是Vue3.5,其中主要包含了几个小改动,我留意到日常最常用的改动就是props了,肯定是用Vue3的人必用的,所以针对性...

Vue 3 生命周期完整指南(vue生命周期及使用)

Vue2和Vue3中的生命周期钩子的工作方式非常相似,我们仍然可以访问相同的钩子,也希望将它们能用于相同的场景。...

救命!这 10 个 Vue3 技巧藏太深了!性能翻倍 + 摸鱼神器全揭秘

前端打工人集合!是不是经常遇到这些崩溃瞬间:Vue3项目越写越卡,组件通信像走迷宫,复杂逻辑写得脑壳疼?别慌!作为在一线摸爬滚打多年的老前端,今天直接甩出10个超实用的Vue3实战技巧,手把...

怎么在 vue 中使用 form 清除校验状态?

在Vue中使用表单验证时,经常需要清除表单的校验状态。下面我将介绍一些方法来清除表单的校验状态。1.使用this.$refs...

取消回复欢迎 发表评论: