【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和你自己的后端对应上即可。

结果展示

相关推荐
这是个栗子几秒前
【Vue3项目】电商前台项目(四)
前端·vue.js·pinia·表单校验·面包屑导航
lay_liu几秒前
springcloud springboot nacos版本对应
spring boot·spring·spring cloud
tumeng07111 分钟前
springboot项目架构
spring boot·后端·架构
LES000LIE4 分钟前
Spring Cloud
后端·spring·spring cloud
mldlds25 分钟前
Spring Boot应用关闭分析
java·spring boot·后端
zjjsctcdl26 分钟前
Spring Boot与MyBatis
spring boot·后端·mybatis
yoyo_zzm36 分钟前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
用户4055948025037 分钟前
对组件内使用:deep()修改自身样式和样式穿透的记录
vue.js
何中应38 分钟前
<el-tree>标签问题
前端·vue.js·elementui