EasyExcel导出Excel指定属性列

背景:

        所见即所得,动态列表导出。前端传递需要导出的字段,后端根据前端的字段导出对应字段列的值到Excel

1.所需JAR包

        
        
            com.alibaba
            easyexcel
            2.2.7
        

2.导出实体类

package com.bulls.bigdataexport.controller;

import cn.afterturn.easypoi.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class DemoDTO {
    @ExcelIgnore
    private int id;

    @ExcelProperty("姓名")
    private String name;

    @ExcelProperty("编号")
    private String code;

    @ExcelProperty("年龄")
    private String age;

    @ExcelProperty("性别")
    private String sex;

    @ExcelProperty("地址")
    private String address;

    @ExcelProperty("出生时间")
    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    private Date birthday;
}

3.实现代码:

    @GetMapping("/exportExcel")
    public void test(HttpServletResponse response, String column) {
        try {
            exportExcel(response, column);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void exportExcel(HttpServletResponse response, String column) throws IOException {
        List demos = new ArrayList<>();
        DemoDTO dto = new DemoDTO();
        dto.setId(1);
        dto.setName("张三");
        dto.setAge("20");
        dto.setCode("0000001");
        demos.add(dto);
        DemoDTO dto1 = new DemoDTO();
        dto1.setId(2);
        dto1.setName("李四");
        dto1.setAge("21");
        dto1.setCode("0000002");
        demos.add(dto1);
        //前端传入的需要导出的列
        Set columns = new HashSet(Arrays.asList(column.split(",")));
        // 测试用
        //这里需要指定用哪个class去写,然后写到第一个sheet,名字为模板
        EasyExcel.write("D:\\excel"+System.currentTimeMillis()+".xlsx", DemoDTO.class)
                .includeColumnFiledNames(columns).sheet("模板")
                .doWrite(demos);

        // 前后端导出
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("ExcelName", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setHeader("fileName",  fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), DemoDTO.class)
                .includeColumnFiledNames(columns).sheet("模板")
                .doWrite(demos);
    }

 4.导出结果展示

EasyExcel导出Excel指定属性列_第1张图片

你可能感兴趣的:(java,SpringBoot,excel,java)