SpringBoot使用EasyExcel实现Excel的导入导出

一、概念

EasyExcel 是一个基于 Java 的、快速、简洁、解决大文件内存溢出的 Excel 处理工具。它能让你在不用考虑性能、内存的等因素的情况下,快速完成 Excel 的读、写等功能。

二、EasyExcel常用注解

注解名称 属性介绍
@ExcelProperty

value属性设置表头的名称

index属性指定列号,从0开始

converter属性可以设置自定义的类型转换

@ExcelIgnore       

导出时忽略该属性
@ColumnWidth       设置表格列的宽度
@DateTimeFormat       设置日期转换格式
@ContentFontStyle 设置单元格内容字体格式
@ContentRowHeight 设置表格行高
@HeadFontStyle         设置标题字体格式
@HeadRowHeight 设置标题行行高
@HeadStyle         设置标题样式
@NumberFormat 设置数字转换格式

三、创建项目并导入相关依赖



    org.projectlombok
    lombok



    com.alibaba
    easyexcel
    3.1.1

四、自定义实体类

package com.example.multipledatabase.vo;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.example.multipledatabase.converter.GenderConverter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.Date;

/**
 * @author qx
 * @date 2023/7/6
 * @des 用户实体类
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserVo {

    /**
     * 用户编号
     */
    @ExcelProperty(value = "用户编号")
    @ColumnWidth(20)
    private Long id;

    /**
     * 用户名
     */
    @ExcelProperty(value = "用户名")
    private String username;

    /**
     * 密码
     */
    @ExcelIgnore
    private String password;

    /**
     * 出生日期
     */
    @ExcelProperty("出生日期")
    @DateTimeFormat("yyyy-MM-dd")
    @ColumnWidth(50)
    private Date birthday;

    /**
     * 性别
     */
    @ExcelProperty(value = "性别", converter = GenderConverter.class)
    private Integer gender;


}

五、创建自定义类型转换类

package com.example.multipledatabase.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.example.multipledatabase.enums.GenderEnum;

/**
 * @author qx
 * @date 2023/7/6
 * @des 性别类型自定义转换类
 */
public class GenderConverter implements Converter {

    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(ReadConverterContext context) {
        // 导入操作把字符串转换为整数类型
        return GenderEnum.convert(context.getReadCellData().getStringValue()).getCode();
    }

    @Override
    public WriteCellData convertToExcelData(WriteConverterContext context) {
        // 导出操作把整数类型转换为字符串类型
        return new WriteCellData<>(GenderEnum.convert(context.getValue()).getData());
    }
}

自定义性别枚举类

package com.example.multipledatabase.enums;

import lombok.Getter;

import java.util.stream.Stream;

/**
 * @author qx
 * @date 2023/7/6
 * @des 性别枚举
 */
@Getter
public enum GenderEnum {
    UNKNOWN(0, "未知"), MALE(1, "男"), FEMALE(2, "女");


    private final Integer code;
    private final String data;

    GenderEnum(Integer code, String data) {
        this.code = code;
        this.data = data;
    }

    public static GenderEnum convert(Integer value) {
        return Stream.of(values()).filter(v -> v.code.equals(value)).findFirst().orElse(UNKNOWN);
    }

    public static GenderEnum convert(String name) {
        return Stream.of(values()).filter(d -> d.data.equals(name)).findFirst().orElse(UNKNOWN);
    }
}

六、Excel导出测试

我们先创建一个Excel导出的工具类,包含导出的参数设置。

代码如下:

package com.example.multipledatabase.util;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author qx
 * @date 2023/7/6
 * @des Excel工具类
 */
public class ExcelUtil {

    /**
     * Excel头部导出封装
     *
     * @param response
     * @param rawFileName
     * @throws UnsupportedEncodingException
     */
    public static void setExcelHeader(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}

最后我们创建用来测试的控制层

package com.example.multipledatabase.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.multipledatabase.util.ExcelUtil;
import com.example.multipledatabase.vo.UserVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author qx
 * @date 2023/7/6
 * @des excel控制层
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    /**
     * 导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void exportUser(HttpServletResponse response) throws IOException {
        ExcelUtil.setExcelHeader(response, "用户列表");
        List userVoList = initUserList();
        EasyExcel.write(response.getOutputStream()).head(UserVo.class).excelType(ExcelTypeEnum.XLSX).sheet("用户列表").doWrite(userVoList);
    }

    /**
     * 初始化数据
     *
     * @return
     */
    private List initUserList() {
        List userVoList = new ArrayList<>();
        userVoList.add(new UserVo(1L, "aa", "123", new Date(), 1));
        userVoList.add(new UserVo(2L, "bb", "123", new Date(), 2));
        userVoList.add(new UserVo(3L, "cc", "123", new Date(), 0));
        return userVoList;
    }
    
}

我们在浏览器访问地址:http://localhost:8080/excel/export

SpringBoot使用EasyExcel实现Excel的导入导出_第1张图片 

 我们打开下载下来的这个excel文件。

SpringBoot使用EasyExcel实现Excel的导入导出_第2张图片

 到这里基本实现了使用EasyExcel导出数据到Excel的结果。

七、导入测试

 在控制层加一个导入的方法

 /**
     * 导入
     */
    @PostMapping("/import")
    public List importUser(MultipartFile file) throws IOException {
        return EasyExcel.read(file.getInputStream())
                .head(UserVo.class)
                .sheet()
                .doReadSync();
    }

我们使用Postman导入excel文件进行测试

SpringBoot使用EasyExcel实现Excel的导入导出_第3张图片

 我们导入成功了,并且返回了excel文件中的数据,而且excel的性别数据转换成了我们需要的整数类型。

你可能感兴趣的:(SpringBoot,excel,Easyexcel,spring,boot,后端)