springboot利用easypoi实现简单导出Excel

vue springboot利用easypoi实现简单导出


前言

今天玩了一下springboot利用easypoi实现excel的导出,以前没玩过导入导出,只不过听说过看别人用过,怎么说呢,想玩就玩一下吧,毕竟结合自己业务场景需要才会考虑是否使用。先简单介绍一下easypoi。


一、easypoi是什么?

1.不太熟悉poi的
2.不想写太多重复太多的
3.只是简单的导入导出的
4.喜欢使用模板的

若poi都不知道的童鞋请自行百度。。。

Easypoi的目标不是替代poi,而是让一个不懂导入导出的快速使用poi完成Excel和word的各种操作,而不是看很多api才可以完成这样工作。

二、使用步骤

1.传送门

因为我也是第一次使用,这里还是先将easypoi的文档放这儿吧:

basedemo.md · 悟耘信息/easypoi - Gitee.com

2.后端springboot

首先引入easypoi所需依赖:

highlighter-hljs 复制代码
       <!--easypoi导入导出-->
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>4.1.3</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-web</artifactId>
			<version>4.1.3</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-annotation</artifactId>
			<version>4.1.3</version>
		</dependency>

或者使用这个:

highlighter-hljs 复制代码
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.0.0</version>
</dependency>

3.1编写实体类(我这里是dto,也一样)

highlighter-hljs 复制代码
package top.wangxingjun.separate.dto;

import cn.afterturn.easypoi.excel.annotation.Excel;
import top.wangxingjun.separate.dto.base.OutputConverter;
import top.wangxingjun.separate.entity.AdminRole;
import top.wangxingjun.separate.entity.User;
import lombok.Data;
import lombok.ToString;

import java.util.List;

/**
 * @author wxj
 * @Date 2020/8/10
 */
@Data
@ToString
public class UserDTO implements OutputConverter<UserDTO, User> {

    @Excel(name = "编号")
    private int id;

    @Excel(name = "账号")
    private String username;

    @Excel(name = "真实姓名")
    private String name;

    @Excel(name = "手机号")
    private String phone;

    @Excel(name = "邮箱")
    private String email;

    @Excel(name = "状态",replace = {"启用_true","禁用_false"})
    private boolean enabled;

}

简单看一下这个 @Excel 注解主要的值:

关于图片路径

着重说明一下这个图片路径,当 type 取值为 2 的时候表示导出为图片,同时配合使用的是 imageType 参数,该参数决定是从 file 读取,还是去数据库读取,默认为从 file 中读取,记得很早之前,有小伙伴图片是直接 base64 存数据库的,不过现在是没有人干这种事了

3.2控制层

直接看代码:

highlighter-hljs 复制代码
    /**
     * 用户信息导出
     */
    @GetMapping("api/exportUser")
    public void exportUser(HttpServletResponse response) throws Exception {
        List<UserDTO> list = userService.list();
        ExcelUtil.exportExcel(list, null, "sheet1", UserDTO.class, "用户信息", response);
    }

没错,就这么几行代码,当然了,还要有个工具类,是我封装好的,网上也有很多的咯。下面看工具类:

highlighter-hljs 复制代码
 package top.wangxingjun.separate.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * @ProjectName: separate
 * @Package: top.wangxingjun.separate.util
 * @ClassName: ExcelUtil
 * @Author: wxj
 * @Description: Excel导入导出工具类
 * @Date: 2020/8/25 10:07
 * @Version: 1.0
 */
@Log4j2
public class ExcelUtil {
    /**
     * Map集合导出
     *
     * @param list     需要导出的数据
     * @param fileName 导出的文件名
     * @param response HttpServletResponse对象
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception{
        defaultExport(list, fileName, response);
    }

    /**
     * 复杂导出Excel,包括文件名以及表名(不创建表头)
     *
     * @param list      需要导出的数据
     * @param title     表格首行标题(不需要就传null)
     * @param sheetName 工作表名称
     * @param pojoClass 映射的实体类
     * @param fileName  导出的文件名(如果为null,则默认文件名为当前时间戳)
     * @param response  HttpServletResponse对象
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   HttpServletResponse response) throws Exception{
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    /**
     * 复杂导出Excel,包括文件名以及表名(创建表头)
     *
     * @param list           需要导出的数据
     * @param title          表格首行标题(不需要就传null)
     * @param sheetName      工作表名称
     * @param pojoClass      映射的实体类
     * @param fileName       导出的文件名
     * @param isCreateHeader 是否创建表头
     * @param response       HttpServletResponse对象
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   boolean isCreateHeader, HttpServletResponse response) throws Exception{
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * 默认导出方法
     *
     * @param list         需要导出的数据
     * @param pojoClass    对应的实体类
     * @param fileName     导出的文件名
     * @param response     HttpServletResponse对象
     * @param exportParams 导出参数实体
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
                                      ExportParams exportParams) throws Exception{
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downloadExcel(fileName, workbook, response);
    }

    /**
     * 默认导出方法
     *
     * @param list     Map集合
     * @param fileName 导出的文件名
     * @param response HttpServletResponse对象
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)throws Exception {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (null != workbook) {
            downloadExcel(fileName, workbook, response);
        }
    }

    /**
     * Excel导出
     *
     * @param fileName Excel导出
     * @param workbook Excel对象
     * @param response HttpServletResponse对象
     */
    public static void downloadExcel(String fileName, Workbook workbook, HttpServletResponse response) throws Exception{
        try {
            if (StringUtils.isEmpty(fileName)) {
                throw new RuntimeException("导出文件名不能为空");
            }
            String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName);
            response.setHeader("FileName", encodeFileName);
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径来导入Excel
     *
     * @param filePath   文件路径
     * @param titleRows  表标题的行数
     * @param headerRows 表头行数
     * @param pojoClass  映射的实体类
     * @return
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception{
        //判断文件是否存在
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            log.error("模板不能为空", e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return list;
    }

    /**
     * 根据接收的Excel文件来导入Excel,并封装成实体类
     *
     * @param file       上传的文件
     * @param titleRows  表标题的行数
     * @param headerRows 表头行数
     * @param pojoClass  映射的实体类
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception{
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            log.error("excel文件不能为空", e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return list;
    }

    /**
     * 文件转List
     *
     * @param file
     * @param pojoClass
     * @param <T>
     * @return
     */
    public static <T> List<T> fileToList(MultipartFile file, Class<T> pojoClass) throws Exception{
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        List<T> list = ExcelUtil.importExcel(file, 1, 1, pojoClass);
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("未解析到表格数据");
        }
        return list;
    }
}

excel导出所需要的都准备好了,下面来看一下我的效果:

相关推荐
别惹CC7 分钟前
Spring AI 进阶之路01:三步将 AI 整合进 Spring Boot
人工智能·spring boot·spring
Stringzhua7 分钟前
Vue中的数据渲染【4】
css·vue.js·css3
柯南二号1 小时前
【Java后端】Spring Boot 集成 MyBatis-Plus 全攻略
java·spring boot·mybatis
javachen__2 小时前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
阿珊和她的猫4 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
加班是不可能的,除非双倍日工资8 小时前
css预编译器实现星空背景图
前端·css·vue3
IT毕设实战小研9 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi9 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
gnip9 小时前
vite和webpack打包结构控制
前端·javascript
一只爱撸猫的程序猿9 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程