easyexcel自定义写文件

74 阅读1分钟

一,pom依赖

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

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

二,springboot设置

@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
    String fileName = "zs.xlsx";
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream())
            .head(head())// 设置表头
            .sheet("模板")// 设置 sheet 的名字
            // 自适应列宽
            .registerWriteHandler(createTableStyle())
            .doWrite(dataList());// 写入数据
}
private static List<List<String>> head() {
    List<List<String>> list = new ArrayList<List<String>>();
    // 第一列表头
    list.add(Collections.singletonList("第1列"));
    list.add(Collections.singletonList("第2列"));
    list.add(Collections.singletonList("第3列"));
    list.add(Collections.singletonList("第4列"));
    return list;
}
private static List dataList() {
    List<List<Object>> list = new ArrayList<List<Object>>();
    for (int i = 0; i < 10; i++) {
        List<Object> data = new ArrayList<Object>();
        data.add("点赞+" + i);
        // date 将会安装 yyyy-MM-dd HH:mm:ss 格式化
        data.add(LocalDate.now().toString());
        data.add(0.56);
        list.add(data);
    }
    return list;
}

三,自定义处理器

private static WriteHandler createTableStyle() {
    // 头的策略
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    // 背景设置为红色
    headWriteCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
    // 设置字体
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short) 20);
    headWriteCellStyle.setWriteFont(headWriteFont);
    headWriteFont.setColor(IndexedColors.WHITE.getIndex());
    // 内容的策略
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

    // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
    HorizontalCellStyleStrategy horizontalCellStyleStrategy =
            new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    return horizontalCellStyleStrategy;
}

四,效果

image.png

另外还可以使用复杂表头,原理是自动合并单元格。