easyExcel实现Excel导出功能

easyExcel导出

此篇仅记录导出功能的实现!

1、导入maven依赖

		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.6</version>
        </dependency>

2、实体类

@Data
public class JobLevel {

    //不需要的的字段使用 @ExcelIgnore
    @ExcelIgnore
    private Integer id;

    @ExcelProperty({"职位名称"})
    private String name;

    @ExcelProperty({"职位等级"})
    private String titleLevel;

    
    //@DateTimeFormat("yyyy-MM-dd")  时间格式转换
    @ExcelProperty({"创建时间"})
    @DateTimeFormat("yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai")
    private Date createDate;

    @ExcelProperty(value={"是否启用"}, converter = CustomBooleanConverter.class)
    private Boolean enabled;

3、和表格模板相对应

@ExcelProperty({"职位名称"})
private String name;

在这里插入图片描述

4、Boolean 类型转换器

package com.carpxt.myhr.controller.config;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

/**
 * @Author: tt
 * @Date: 2020/12/17 20:38
 * @Description: Boolen类型数据转换器  实现Converter接口
 * @Version: 1.0
 */
public class CustomBooleanConverter implements Converter<Boolean> {


    @Override
    public Class supportJavaTypeKey() {
        return null;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return cellData.getBooleanValue();
    }

    @Override
    public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData(value?"是":"否");
    }
}

5、导出代码:

public void downloadJob(HttpServletResponse response) throws IOException {
        List<JobLevel> jobLevelList = jobLevelMapper.getJobLevelList();
        ClassPathResource classPathResource = new ClassPathResource("templates/exportStaTemplate.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
     	// 如果不用模板的方式导出的话,是doWrite
        EasyExcel.write(response.getOutputStream(), JobLevel.class).withTemplate(inputStream).sheet("模板").doFill(jobLevelList);
    }

6、导出效果

在这里插入图片描述

原文地址:https://www.cnblogs.com/kt-ting/p/14487994.html