本文代码: EasyExcelDemo

控制层

@RequestMapping("/multiTableWrite")
public void multiTableWrite(HttpServletResponse response) throws IOException {
    service.multiTableWrite(response);
}

导出模型

public class ExcelDemoDto {
    @ExcelProperty("字符串测试1")
    private String column1;
    @ExcelProperty("字符串测试2")
    private String column2;
    @ExcelProperty("数字测试")
    private BigDecimal number;
    @ExcelProperty("日期测试")
    @DateTimeFormat(value = "yyyy-MM-dd")
    private Date date;
}

实现层

public void multiTableWrite(HttpServletResponse response) throws IOException {
    ServletOutputStream outputStream = EasyExcelUtil.getOutputStream(response);
    ExcelWriter writer = EasyExcel.write(outputStream).build();
    WriteSheet sheet = EasyExcel
        .writerSheet(0)
        // table 会继承sheet的配置,多table导出时会重复生成多个头
        .needHead(Boolean.FALSE)
        .sheetName("多表头导出测试")
        .build();

    // table1 手动设置头
    WriteTable table1 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).build();
    List<List<String>> head = new ArrayList<>();
    List<String> col1 = Arrays.asList("table1-列1");
    List<String> col2 = Arrays.asList("table1-列2");
    List<String> col3 = Arrays.asList("table1-列3");
    List<String> col4 = Arrays.asList("table1-列4");
    head.add(col1);
    head.add(col2);
    head.add(col3);
    head.add(col4);
    table1.setHead(head);
    List<List<Object>> exportData = new ArrayList<>();
    List<Object> row1 = Arrays.asList(1,2,3,4);
    List<Object> row2 = Arrays.asList("a","b","c","d");
    exportData.add(row1);
    exportData.add(row2);

    // table2 使用模型设置头
    WriteTable table2 = EasyExcel.writerTable(1).head(ExcelDemoDto.class).needHead(Boolean.TRUE).build();

    writer.write(exportData     ,sheet,table1);
    writer.write(new ArrayList(),sheet,table2);
    writer.finish();
}

导出效果

多表头导出效果

最后修改:2022 年 04 月 26 日
请博主喝杯咖啡~~~