【EasyExcel】在SpringBoot+VUE项目中引入EasyExcel实现对数据的导出(封装工具类)

在SpringBoot+VUE项目中引入EasyExcel实现导入导出

一、引入EasyExcel

通过maven引入,坐标如下:

xml 复制代码
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.3.2</version>
        </dependency>

二、后端代码演示

下面以权限系统中的角色列表为案例,演示如何导出数据

实体类

java 复制代码
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.*;
import com.alibaba.excel.enums.poi.HorizontalAlignmentEnum;
import com.alibaba.excel.enums.poi.VerticalAlignmentEnum;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * 角色excel
 *
 * @author ez4sterben
 * @date 2023/07/17
 */
@ContentRowHeight(30)
@HeadRowHeight(20)
@ColumnWidth(25)
@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment =  VerticalAlignmentEnum.CENTER)
@Data
public class RoleExcelVO {
    /**
     * 角色名称
     */
    @ExcelProperty(value = "角色名称")
    private String roleName;

    /**
     * 权限字符
     */
    @ExcelProperty(value = "权限字符")
    private String permission;

    /**
     * 角色状态(0停用,1正常)
     */
    @ExcelProperty(value = "角色状态")
    private String status;

    /**
     * 备注
     */
    @ExcelProperty(value = "备注")
    private String remark;
    /**
     * 创建时间
     */
    @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
    @ExcelProperty(value = "创建时间")
    private LocalDateTime createTime;

}

工具类

通过@Component把工具类交给spring管理,在需要使用的地方使用@Resource注入即可

将泛型设置为 " ? ",来表示任意类型,可以通过这一个方法完成所有类的相似导出操作,如果要投入使用的话可以对arrayList和excelVO的类型是否相同进行判断,这里没有进行判断。

EasyExcel工具类

java 复制代码
import com.alibaba.excel.EasyExcel;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * 简单excel工具类
 *
 * @author ez4sterben
 * @date 2023/07/17
 */
@Component
public class EasyExcelUtil {

    public static final String XLSX = ".xlsx";

    public String export(ArrayList<?> arrayList, Class<?> excelVO, String sheetName) {
        String fileName = System.currentTimeMillis() + XLSX;
        EasyExcel.write(fileName, excelVO).sheet(sheetName).doWrite(arrayList);
        return fileName;
    }
}

Excel输出工具类

如果你使用的是微服务架构建议考虑该工具类的位置不要和基本模块放在一起,而是和Controller放在同一个模块,下面的常量定义大可不必这么做,但个人认为代码规范还是很重要的。另外输出流的部分代码还可以改进,欢迎提出建议。

java 复制代码
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 基础excel输出工具
 *
 * @author ez4sterben
 * @date 2023/07/18
 */
public class BaseExcelOutPutUtil {

    public static FileInputStream FILE_INPUT_STREAM;
    
    public static ServletOutputStream SERVLET_OUTPUT_STREAM;

    public static final String EXCEL = "application/vnd.ms-excel";

    public static final String CONTENT_DISPOSITION = "Content-Disposition";

    public static final String ATTACHMENT = "attachment;";

    public static final Integer SUCCESS_CODE = 200;

    public static void exportExcel(HttpServletResponse response, String filePath) throws IOException {
        try {
            FILE_INPUT_STREAM = new FileInputStream(filePath);
            SERVLET_OUTPUT_STREAM = response.getOutputStream();

            response.setContentType(EXCEL);
            response.setHeader(CONTENT_DISPOSITION, ATTACHMENT);
            response.setStatus(SUCCESS_CODE);

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = FILE_INPUT_STREAM.read(bytes)) > 0) {
                SERVLET_OUTPUT_STREAM.write(bytes, 0, len);
            }
            SERVLET_OUTPUT_STREAM.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭流
            SERVLET_OUTPUT_STREAM.close();
            FILE_INPUT_STREAM.close();
            new File(filePath).delete();
        }
    }

}

业务层

java 复制代码
	@Resource
    private EasyExcelUtil easyExcelUtil;

	public static final String SHEET_NAME = "角色表";
    
	/**
     * 导出
     *
     * @param ids id
     * @return {@link String}
     * @throws IOException ioexception
     */
    @Override
    public String export(List<Long> ids) throws IOException {
    	// 前端传参ids,查询数据
        List<RolePO> rolePOS = this.listByIds(ids);
        ArrayList<RoleExcelVO> roleExcelVOS = new ArrayList<>();
        rolePOS.forEach(rolePO -> {
        	// 通过hutool的BeanUtils把内容抄送给roleExcelVO
            RoleExcelVO roleExcelVO = new RoleExcelVO();
            BeanUtils.copyProperties(rolePO,roleExcelVO);
            roleExcelVOS.add(roleExcelVO);
        });
        return easyExcelUtil.export(roleExcelVOS,RoleExcelVO.class,SHEET_NAME);
    }

由于我们刚才已经封装过工具类,那么这里不限于角色表的导出,还可以是其他的任何表,比如我要导出用户表,那么我只需要扒这部分代码写入用户的业务层就可以

Controller层

java 复制代码
	/**
     * 导出
     *
     * @return {@link Result}<{@link List}<{@link BusinessVO}>>
     */
    @PostMapping("/export")
    public void export(@RequestBody List<Long> ids, HttpServletResponse response) {
        String filePath;
        try {
            filePath = roleService.export(response,ids);
            BaseExcelOutPutUtil.exportExcel(response,filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

到此为止后端的代码就展示完毕,其实还可以把导出统一封装在一起,但是目前对于我这个小项目完全是够用了,已经可以省去我很多内容了,读者有兴趣可以自行封装。下面会给各位展示前端代码。

前端VUE调用

java 复制代码
	// 导出
    handleExport() {
      axios({
        method: "post",
        data: this.selectedRoles, // 这里写ids []
        url: this.urls.export, // 这里写你自己的后端url
        responseType: "blob"
      }).then((res) => {
        const blob = new Blob([res.data]);
        const a = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        a.href = href;
        a.download = '角色表权限.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(href);
      }).catch((error) => {});
    },

下载通过blob实现,博主前端写的不规范,请自行更改。

data和url和你自己的后端对应上即可。

结果展示

相关推荐
weyyhdke5 分钟前
基于SpringBoot和PostGIS的省域“地理难抵点(最纵深处)”检索及可视化实践
java·spring boot·spring
ILYT NCTR11 分钟前
【springboot】Spring 官方抛弃了 Java 8!新idea如何创建java8项目
java·spring boot·spring
2601_949816161 小时前
spring.profiles.active和spring.profiles.include的使用及区别说明
java·后端·spring
QQ5110082851 小时前
基于区块链的个人医疗咨询挂号信息系统vue
前端·vue.js·区块链
项目帮1 小时前
Java毕设选题推荐:基于springboot区块链的电子病历数据共享平台设计与实现【附源码、mysql、文档、调试+代码讲解+全bao等】
java·spring boot·课程设计
helx822 小时前
SpringBoot实战(三十二)集成 ofdrw,实现 PDF 和 OFD 的转换、SM2 签署OFD
spring boot·后端·pdf
rOuN STAT3 小时前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
赵丙双4 小时前
spring boot 排除自动配置类的方式和原理
java·spring boot·自动配置
bilI LESS5 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
Chan165 小时前
MCP 开发实战:Git 信息查询 MCP 服务开发
java·开发语言·spring boot·git·spring·java-ee·intellij-idea