EasyExcel使用模板导出复杂Excel

1)添加easyexlce的依赖

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>easyexcelartifactId>
    <version>3.0.0-beta1version>
dependency>

2)添加excel模板文件
EasyExcel使用模板导出复杂Excel_第1张图片
实现的效果:
EasyExcel使用模板导出复杂Excel_第2张图片

3)导出

@GetMapping("/export/use/template")
public void downloadUseTemplate(HttpServletResponse response) throws Exception {
    // 下载excel
    String fileName = "使用模板导出.xlsx";
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

    // 加载模板
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
    // 输出到response
    ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
            .withTemplate(inputStream)
            .excelType(ExcelTypeEnum.XLSX).build();

    // 得到sheet
    WriteSheet writeSheet = EasyExcel.writerSheet().build();

    // 单个字段填充
    Map<String, Object> map = new HashMap<>();
    map.put("weekAdd",100);
    map.put("monthAdd",200);
    map.put("total",300);
    excelWriter.fill(map, writeSheet);

    // 列表竖向填充
    List<DetailDTO> details = new ArrayList<>();
    details.add(new DetailDTO(new SimpleDateFormat("yyyy-MM-dd").parse("2023-12-10"), 100));
    details.add(new DetailDTO(new SimpleDateFormat("yyyy-MM-dd").parse("2023-12-11"), 80));
    details.add(new DetailDTO(new SimpleDateFormat("yyyy-MM-dd").parse("2023-12-12"), 200));
    excelWriter.fill(new FillWrapper("details", details), writeSheet);

    // 列表横向填充
    FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
    excelWriter.fill(new FillWrapper("week", details),fillConfig, writeSheet);

    excelWriter.finish();

}

完整的源码下载https://github.com/xjs1919/enumdemo下面的easyexcel-upload-demo
done!

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