[EasyExcel] Introduce EasyExcel in the SpringBoot+VUE project to realize the export of data (encapsulation tool class)

Introduce EasyExcel in SpringBoot+VUE project to realize import and export

1. Introducing EasyExcel

Imported through maven, the coordinates are as follows:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.3.2</version>
        </dependency>

2. Back-end code demo

The following takes the role list in the permission system as a case to demonstrate how to export data

Entity class

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;

}

Tools

Give the tool class to spring management through @Component, and use @Resource injection where it needs to be used

Set the generic type to " ? " to represent any type. This method can be used to complete similar export operations of all classes. If you want to put it into use, you can judge whether the types of arrayList and excelVO are the same. No judgment is made here.

EasyExcel tool class

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 output tool class

If you are using a microservice architecture, it is recommended to consider that the location of the tool class should not be placed with the basic module, but in the same module as the Controller. The following constant definitions do not need to do this, but I personally think that the code specification is still very important. In addition, part of the code of the output stream can also be improved, and suggestions are welcome.

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();
        }
    }

}

Business Layer

	@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);
    }

Since we have encapsulated the tool class just now, this is not limited to the export of the role table, but can also be any other table. For example, if I want to export the user table, then I only need to scrape this part of the code and write it into the user's business layer.

Controller layer

	/**
     * 导出
     *
     * @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);
        }
    }

So far, the back-end code has been displayed. In fact, the export can also be packaged together, but it is enough for my small project at present, and it can save me a lot of content. Readers who are interested can package it by themselves. The front-end code will be shown below.

Front-end VUE call

	// 导出
    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) => {
    
    });
    },

The download is realized through blob, and the blogger’s front-end writing is not standardized, please change it yourself.
The data and url can correspond to your own backend.

Result display

insert image description here

Guess you like

Origin blog.csdn.net/qq_51383106/article/details/131770176
Recommended