easyexcel 动态列导出

发布于:2024-04-08 ⋅ 阅读:(124) ⋅ 点赞:(0)

1. 引入easyexcel

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

2.导出write

public void export(HttpServletResponse response) {
        try {
            String fileName = "测试导出动态列" + System.currentTimeMillis();

            Set<String> includeColumnFiledNames = new HashSet<>();
            includeColumnFiledNames.add("title");
            includeColumnFiledNames.add("openId");
            List<Category> categoryList = getAllCategory();
            List<CategoryExport> categoryExports = BeanUtil.copyToList(categoryList, CategoryExport.class);
            response.setContentType("application/vnd.ms-excel");// 设置文本内省
            response.setCharacterEncoding("utf-8");// 设置字符编码
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx"); // 设置响应头
            ExcelWriterBuilder write = EasyExcel.write(response.getOutputStream(), CategoryExport.class);
            if (includeColumnFiledNames.size() > 0) {
                write.includeColumnFieldNames(includeColumnFiledNames);
            }
            write.sheet("模板").doWrite(categoryExports); //用io流来写入数据
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.导出类

@Data
public class CategoryExport implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    @ExcelProperty("openId")
    private String openId;
    @ExcelProperty("priority")
    private Integer priority;
    @ExcelProperty("标题")
    private String title;
}