返回顶部
分享到

使用EasyPoi实现多Sheet页导出的代码

java 来源:互联网 作者:佚名 发布时间:2025-03-08 21:16:31 人浏览
摘要

因多次遇到导出多Sheet页的需求,故记录下来,以备后续参考使用 一、Pom依赖 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 !-- 集成easypoi组件 .导出excel http://easypoi.mydoc.io/ -- dependency groupIdcn.afterturn/groupId arti

因多次遇到导出多Sheet页的需求,故记录下来,以备后续参考使用

一、Pom依赖

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<!-- 集成easypoi组件 .导出excel http://easypoi.mydoc.io/ -->

            <dependency>

                <groupId>cn.afterturn</groupId>

                <artifactId>easypoi-base</artifactId>

                <version>3.2.0</version>

            </dependency>

            <dependency>

                <groupId>cn.afterturn</groupId>

                <artifactId>easypoi-web</artifactId>

                <version>3.2.0</version>

            </dependency>

            <dependency>

                <groupId>cn.afterturn</groupId>

                <artifactId>easypoi-annotation</artifactId>

                <version>3.2.0</version>

            </dependency>

二、主方法

1

2

3

4

5

6

7

8

SXSSFWorkbook workbook = new SXSSFWorkbook();

try {

                workbook = this.getSheetsList(notQualifiedSumDeptCountVos, locale);

                return workbook;

            } catch (Exception e) {

                log.error("错误",e);

                return null;

            }

三、拼接多Sheet页

1

2

3

4

5

6

7

8

private SXSSFWorkbook getSheetsList(List<Vo> notQualifiedSumDeptCountVos, Locale locale){

        // 点检项排名导出多sheet页

        List<Map<String, Object>> sheetsList = new ArrayList<>();

        // 创建数据概览1-不合格次数的sheet

        this.getNotQualifiedSumExportSheet(notQualifiedSumDeptCountVos, sheetsList, locale);

        SXSSFWorkbook workbook = ExcelUtils.exportExcel(sheetsList);

        return workbook;

    }

四、获取单个Sheet页

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

private void getNotQualifiedSumExportSheet(List<NotQualifiedSumDeptCountVo> notQualifiedSumDeptCountVos, List<Map<String, Object>> sheetsList, Locale locale){

        if (CollectionUtil.isNotEmpty(notQualifiedSumDeptCountVos)) {

            // 创建数据概览1-不合格次数的sheet使用的map

            Map<String, Object> notQualifiedSumExportMap = new HashMap<>(16);

            String notQualifiedSumTitle = messageSource.getMessage("export.check.item.rank0.not.qualified.sum.title", null, locale);

            String notQualifiedSumSheetName = messageSource.getMessage("export.check.item.rank.not.qualified.sheet.name", null, locale);

            ExportParams notQualifiedSumExportParams = new ExportParams(notQualifiedSumTitle, notQualifiedSumSheetName, ExcelType.XSSF);

            List<ExcelExportEntity> notQualifiedSumColList = new ArrayList<>();

            List<Map<String,Object>> notQualifiedSumResList = new ArrayList<>();

            try {

                ExcelUtils.getExcelExportMap(notQualifiedSumColList, notQualifiedSumResList, notQualifiedSumDeptCountVos, NotQualifiedSumDeptCountVo.class, locale);

            } catch (Exception e) {

                log.error("getNotQualifiedSumExportSheet", e);

            }

            notQualifiedSumExportMap.put("title", notQualifiedSumExportParams);

            notQualifiedSumExportMap.put("entityList", notQualifiedSumColList);

            notQualifiedSumExportMap.put("data", notQualifiedSumResList);

            sheetsList.add(notQualifiedSumExportMap);

        }

    }

五、ExcelUtils

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

package com.ovopark.check.util;

 

import cn.afterturn.easypoi.excel.annotation.Excel;

import cn.afterturn.easypoi.excel.entity.ExportParams;

import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;

import cn.hutool.core.util.ReflectUtil;

import com.ovopark.check.service.impl.MyExcelExportService;

import java.lang.reflect.Field;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.List;

import java.util.Locale;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import org.springframework.context.MessageSource;

 

/**

 * @author: chenheng

 * @create: 2022-05-25 09:20

 * @description:

 **/

public class ExcelUtils {

  /**

   * 用于国际化

   */

  private static MessageSource messageSource = SpringContextUtils.getBean(MessageSource.class);

  /**

   * 一个excel 创建多个sheet

   * @param list

   * @return

   */

  public static SXSSFWorkbook exportExcel(List<Map<String, Object>> list) {

    SXSSFWorkbook workbook = new SXSSFWorkbook();

    for (Map<String, Object> map : list) {

      MyExcelExportService service = new MyExcelExportService();

      service.createSheetWithList(workbook, (ExportParams) map.get("title"), ExportParams.class,

          (List<ExcelExportEntity>) map.get("entityList"), (Collection<?>) map.get("data"));

    }

    return workbook;

  }

 

  public static void getExcelExportMap(List<ExcelExportEntity> colList, List<Map<String,Object>> resList,

      List list, Class<?> pojoClass, Locale locale) throws IllegalAccessException {

    Field[] classFields = ReflectUtil.getFields(pojoClass);

    //需要导出的属性list

    List<Field> newFields = new ArrayList<>();

    for (Field field : classFields) {

      Excel excel = field.getAnnotation(Excel.class);

      if (excel != null) {

        ExcelExportEntity entity = new ExcelExportEntity();

        entity.setName(messageSource.getMessage(excel.name(), null, locale));

        entity.setKey(field.getName());

        entity.setOrderNum(Integer.parseInt(excel.orderNum()==null?"0":excel.orderNum()));

        colList.add(entity);

        newFields.add(field);

      }

    }

    //数据体

    for (Object obj : list) {

      Map<String, Object> map = new HashMap<>();

      for (Field field : newFields) {

        // 仅在获取用private修饰属性使用

        field.setAccessible(true);

        map.put(field.getName(), field.get(obj)!=null?field.get(obj):"-");

      }

      resList.add(map);

    }

  }

 

}

六、MyExcelExportService

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

package com.ovopark.check.service.impl;

 

import cn.afterturn.easypoi.excel.annotation.ExcelTarget;

import cn.afterturn.easypoi.excel.entity.ExportParams;

import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;

import cn.afterturn.easypoi.excel.export.ExcelExportService;

import cn.afterturn.easypoi.exception.excel.ExcelExportException;

import cn.afterturn.easypoi.exception.excel.enums.ExcelExportEnum;

import cn.afterturn.easypoi.util.PoiPublicUtil;

import java.lang.reflect.Field;

import java.util.Collection;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.apache.poi.ss.usermodel.Workbook;

 

/**

 * @author: chenheng

 * @create: 2022-05-25 09:26

 * @description:

 **/

@Slf4j

public class MyExcelExportService extends ExcelExportService {

 

  public void createSheetWithList(Workbook workbook, ExportParams entity, Class<?> pojoClass, List<ExcelExportEntity> entityList, Collection<?> dataSet) {

    if (LOGGER.isDebugEnabled()) {

      LOGGER.debug("Excel export start ,class is {}", pojoClass);

      LOGGER.debug("Excel version is {}",

          entity.getType().equals(ExcelType.HSSF) ? "03" : "07");

    }

    if (workbook == null || entity == null || pojoClass == null || dataSet == null) {

      throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);

    }

    try {

      List<ExcelExportEntity> excelParams = entityList;

      // 得到所有字段

      Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);

      ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class);

      String targetId = etarget == null ? null : etarget.value();

      getAllExcelField(entity.getExclusions(), targetId, fileds, excelParams, pojoClass,

          null, null);

      //获取所有参数后,后面的逻辑判断就一致了

      createSheetForMap(workbook, entity, excelParams, dataSet);

    } catch (Exception e) {

      LOGGER.error(e.getMessage(), e);

      throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, e.getCause());

    }

  }

}


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。

您可能感兴趣的文章 :

原文链接 :
    Tag :
相关文章
  • 使用EasyPoi实现多Sheet页导出的代码
    因多次遇到导出多Sheet页的需求,故记录下来,以备后续参考使用 一、Pom依赖 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 !-- 集成easypoi组件 .导出excel ht
  • idea导入若依项目教程

    idea导入若依项目教程
    IDEA导入若依管理系统 项目官网地址:https://gitee.com/y_project/RuoYi-Vue 前提 系统需求: JDK = 1.8 MySQL = 5.5 Maven = 3.0 redis 必须启动(可以下载一个
  • Java中实现订单超时自动取消功能(最新推荐)

    Java中实现订单超时自动取消功能(最新推荐)
    在开发中,我们会遇到需要延时任务的业务场景,例如:用户下单之后未在规定的时间内支付成功,该订单会自动取消; 用户注册成功15分
  • 阿里巴巴TransmittableThreadLocal使用介绍
    ThreadLocal在上下文的数据传输上非常的方便和简洁。 工业实践中,比较常用的有三个,ThreadLocal、InheritableThreadLocal、TransmittableThreadLocal,那
  • SpringBoot使用Jackson介绍
    概述 Springboot配置JackSon处理类属性,JavaBean序列化为JSON格式,常用框架:阿里fastjson,谷歌gson、Jackson等。 ① 性能:Jackson Fastjson Gson 同个结
  • springboot结合JWT实现单点登录的代码

    springboot结合JWT实现单点登录的代码
    JWT实现单点登录 登录流程: 校验用户名密码-生成随机JWT Token-返回给前端。之后前端发请求携带该Token就能验证是哪个用户了。 校验流程:
  • java正则表达式匹配Matcher类的使用
    Matcher类 用法 在 Java 中,Matcher类是用于匹配正则表达式的工具,而group()方法是Matcher类中的一个重要方法,用于提取匹配结果中的捕获组(
  • Java基础面试真题:String为什么是不可变的?

    Java基础面试真题:String为什么是不可变的?
    + 目录 今天来分享一道群友去阿里云面试遇到的 Java 基础面试真题:String、StringBuffer、StringBuilder的区别?String为什么是不可变的?。 网站很
  • 在Spring Boot Web应用程序中序列化枚举

    在Spring Boot Web应用程序中序列化枚举
    枚举类型在定义应用程序域内有限且明确的值集方面非常有效,有助于避免代码中出现无效状态。 应用场景 以下以一个Spring Boot 3.3.x 和 M
  • Item记录线程安全的介绍

    Item记录线程安全的介绍
    确保并发访问安全:线程安全记录的必要性 类如何处理并发访问对于其使用者至关重要,这应被视为类契约的一部分。 错误地假设线程安全
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计