使用Apache POI和EasyExcel生成Excel文件(三)

223 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第二十五天,点击查看活动详情


上面两章为使用Apache poi生成Excel的方式,接着说easyExcel生成excel的方式。

  1. 简介

EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。

  1. 引入jar包
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.8</version>
</dependency>

简单生成Excel文档

  1. 生成Excel对应的对象模型
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
//标题行的高度设置
@HeadRowHeight(17)
//标题字体及字体大小设置
@HeadFontStyle(fontName = "黑体", fontHeightInPoints = 12, bold = false)
//内容行的高度设置
@ContentRowHeight(17)
/内容字体设置
@ContentFontStyle(fontHeightInPoints = 12)
//内容居中等格式设置
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER, verticalAlignment = VerticalAlignment.CENTER)
public class TestResp {

    //设置导出Excel忽略该字段
    @ExcelIgnore
    private int id;

    //Excel标题字段
    @ExcelProperty("序号")
    //Excel字段宽度设置
    @ColumnWidth(8)
    private int orderNo;
}
  1. 通过list数据生成Excel文件
List<TestResp> resps = new ArrayList();
//数据赋值
resps.add(....);

// 设置头信息
response.setContentType("application/vnd.ms-excel;charset=utf-8");
// 文件名URLEncode
String fileName = "测试导出文件";
try {
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
    log.error("测试导出文件文件名编码出错:filename: {}", fileName, e);
}
//设置Header
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

try (
        ServletOutputStream out = response.getOutputStream()
) {
    //写入数据
    EasyExcel.write(out).sheet("测试").head(TestResp.class).doWrite(resps);
} catch (IOException e) {
    log.error("测试文件写出失败", e);
}

生成多行表头Excel文档

String title1 = "第一行表头";
String title2 = "第二行";
List<TestResp> resps = (List<TestResp>) obj.getRetData();
//多行表头下方正式数据的表头
List<String> titles = new ArrayList<String>() {{
    add("列一");
    add("列二");
    add("列三");
    。。。
}};

// 表头
List<List<String>> heads = new ArrayList<List<String>>();
//将多个表头放入list数据中
titles.stream().forEach(t -> {
    List<String> head = new ArrayList<String>() {{
        add(title1);
        add(title2);
        add(t);
    }};
    heads.add(head);
});

// 设置头信息
response.setContentType("application/vnd.ms-excel;charset=utf-8");
// 文件名URLEncode
String fileName = "测试导出文件";
try {
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
    log.error("测试导出文件文件名编码出错:filename: {}", fileName, e);
}
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

try (
        ServletOutputStream out = response.getOutputStream()
) {
    EasyExcel.write(out).sheet("测试").head(heads).head(TestResp.class).doWrite(resps);
} catch (IOException e) {
    log.error("测试文件写出失败", e);
}