周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. 后端
  3. java
  4. 正文

集成easypoi实现excel多sheet导出

2023年 3月 9日 719点热度 0人点赞 0条评论

环境配置

  • 实现excel多sheet工作表的导入导出功能,我们还是得依赖于easypoi来做。所以只需要在pom.xml依赖中加上如下easypoi的starter依赖包即可
<!--easypoi依赖,excel导入导出-->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.3.0</version>
</dependency>

多sheet工作表excel导出

  • 如下我们先分别来定义两个excel导出vo,分不同的sheet存放不同的数据。

  • 先来定义两个导入实体类。

    • ExportExcelLog.java
    @Data
    public class ExportExcelLog implements Serializable {
        private static final long serialVersionUID = 1L;
        /**
         * @Excel 作用在一个filed上面,对列的描述
         * @param name 列名
         * @param orderNum 下标,从0开始。
         */
        @Excel(name = "url", width = 20.0)
        private String url;
        @Excel(name = "ip", width = 20.0)
        private String ip;
        //字段是Date类型则不需要设置databaseFormat
        @Excel(name = "请求时间", format = "yyyy-MM-dd", width = 20.0)
        private Date operationTime;
        @Excel(name = "接口返回状态码", width = 20.0)
        private int code;
    }
    • ExportExcelUser.java
    @Data
    public class ExportExcelUser implements Serializable {
        private static final long serialVersionUID = 1L;
        /**
         * @Excel 作用在一个filed上面,对列的描述
         * @param name 列名
         * @param orderNum 下标,从0开始。
         */
        @Excel(name = "姓名", width = 10.0)
        private String name;
        @Excel(name = "年龄", width = 10.0)
        private Integer age;
        //字段是Date类型则不需要设置databaseFormat
        @Excel(name = "出生年月", format = "yyyy-MM-dd", width = 20.0)
        private Date bornDate;
        //如果数据库如果是string类型,这个需要设置这个数据库时间格式  format:输出时间格式
        @Excel(name = "入学时间", databaseFormat = "yyyyMMdd", format = "yyyy-MM-dd", width = 20.0)
        private String enterSchoolTime;
        //replace:单元格下拉框,_0表示下拉顺序   suffix:文字后缀 比如:男->男生
        @Excel(name = "性别", width = 10.0, replace = {"男_0", "女_1"}, suffix = "生", addressList = true)
        private String sex;
        @Excel(name = "地址", width = 30.0)
        private String address;
        @Excel(name = "头像", type = 2, width = 30.0, height = 30.0, imageType = 1)
        private String image;
        @Excel(name = "用户描述", width = 20.0)
        private String describes;
    }
  • Controller添加excel导入方法

    • 接下来,我们定义一个excel导出方法,目的是提供一个口子,好方便自己通过浏览器访问进行测试代码的完整性。
    /**
     * excel多sheet导出
     */
    @GetMapping("/export-for-sheets")
    @ApiOperation(value = "excel多sheet导出", notes = "excel多sheet导出")
    public void exportSheetUsers(HttpServletResponse response) {
        userService.exportSheetUsers(response);
    }
  • 定义导入接口

    /**
    * excel多sheet导出
    */
    void exportSheetUsers(HttpServletResponse response);
  • 实现导入方法(核心)

    • 具体实现代码,UserServiceImpl.java
    /**
     * excel多sheet导出
     */
    @Override
    public void exportSheetUsers(HttpServletResponse response) {
        //功能描述:把同一个表格多个sheet测试结果重新输出,
        Workbook workBook = null;
        try {
            // 创建参数对象(用来设定excel的sheet1内容等信息)
            ExportParams userExportParams = new ExportParams();
            // 设置sheet得名称
            userExportParams.setSheetName("用户表");
            // 设置sheet表头名称
            userExportParams.setTitle("用户列表");
            // 创建sheet1使用得map
            Map userExportMap = new HashMap<>();
            // title的参数为ExportParams类型,目前仅仅在ExportParams中设置了sheetName
            userExportMap.put("title", userExportParams);
            // 模版导出对应得实体类型
            userExportMap.put("entity", ExportExcelUser.class);
            //转成导出vo类型
            List users = this.changeType(this.list());
            // sheet1中要填充得数据
            userExportMap.put("data", users);
            // 创建参数对象(用来设定excel的sheet2内容等信息)
            ExportParams logInfoExportParams = new ExportParams();
            logInfoExportParams.setTitle("日志列表");
            logInfoExportParams.setSheetName("日志表");
            // 创建sheet2使用的map
            Map logInfoExportMap = new HashMap<>();
            logInfoExportMap.put("title", logInfoExportParams);
            logInfoExportMap.put("entity", ExportExcelLog.class);
            //查询log数据 
            List logInfoEntitys = logInfoMapper.selectList(new QueryWrapper<>());
            //转成导出vo类型
            List logInfos = this.changeInfoType(logInfoEntitys);
            // sheet2中要填充得数据
            logInfoExportMap.put("data", logInfos);
            // 将sheet1、sheet2使用得map进行包装
            List> sheetsList = new ArrayList<>();
            //后续增加sheet组,则后面继续追加即可;
            sheetsList.add(userExportMap);
            sheetsList.add(logInfoExportMap);
            // 执行方法
            workBook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
            //设置编码格式
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //设置内容类型
            response.setContentType("application/octet-stream");
            //设置头及文件命名。
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户及操作日志导出.xls", StandardCharsets.UTF_8.name()));
            //写出流
            workBook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workBook != null) {
                try {
                    //强行关流
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2023年 3月 9日

周凯

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号