Skip to content

Excel默认导出

清沐 edited this page Nov 17, 2023 · 26 revisions

默认导出采用普通方式导出List< Bean >,适合小数据量场景,如数据量很大-10万+,建议使用DefaultStreamExcelBuilder,避免内存占用过多。

默认导出3.0.0.RC版本及其后续,底层采用的是DefaultStreamExcelBuilder.

导出需使用到如下注解

  1. @ExcelModel(includeAllField,excludeParent,workbookType,sheetName,useFieldNameAsTitle,defaultValue)(可选,用于全局设定,一般情况下只需要使用sheetName)
  2. @IgnoreColumn(可选,用于排出不需要导出的字段)
  3. @ExcelColumn(title,order,format,groups,defaultValue,style)

对应注解详情请见:注解

默认导出默认计算宽度、斑马线背景色,若无需上述样式,请调用 noStyle() 方法

附件导出示例:

@GetMapping("/default/excel/example")
public void defaultBuild(HttpServletResponse response) throws Exception {
    List<ArtCrowd> dataList = this.getDataList();
    Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
            .build(dataList);
    // for javax.servlet
    AttachmentExportUtil.export(workbook, "艺术生信息", response);
    
    // for jakarta.servlet
    AttachmentV2ExportUtil.export(workbook, "艺术生信息", response);
}

附件加密导出示例:

@GetMapping("/default/excel/example")
public void defaultBuild(HttpServletResponse response) throws Exception {
    List<ArtCrowd> dataList = this.getDataList();
    Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
            .build(dataList);
    // for javax.servlet
    AttachmentExportUtil.encryptExport(workbook, "艺术生信息", response,"123456");

    // for jakarta.servlet
    AttachmentV2ExportUtil.encryptExport(workbook, "艺术生信息", response,"123456");
}

文件导出示例:

List<ArtCrowd> dataList = this.getDataList();
Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
         .build(dataList);
FileExportUtil.export(workbook, new File("/User/demo.xlsx"));

文件加密导出示例:

List<ArtCrowd> dataList = this.getDataList();
Workbook workbook = DefaultExcelBuilder.of(ArtCrowd.class)
         .build(dataList);
FileExportUtil.encryptExport(workbook, new File("/User/demo.xlsx"),"123456");

数据获取:

private List<ArtCrowd> getDataList() {
    List<ArtCrowd> dataList = new ArrayList<>(1000);
    for (int i = 0; i < 1000; i++) {
        ArtCrowd artCrowd = new ArtCrowd();
         artCrowd.setName("李四");
         artCrowd.setAge(18);
         artCrowd.setGender("Woman");
         artCrowd.setPaintingLevel("一级证书");
         artCrowd.setDance(true);
         artCrowd.setAssessmentTime(LocalDateTime.now());
         artCrowd.setHobby("钓鱼");
        dataList.add(artCrowd);
    }
    return dataList;
}

@ExcelModel(sheetName = "艺术生")
public class ArtCrowd {

    @ExcelColumn(order = 0, title = "姓名")
    private String name;

    @ExcelColumn(order = 1, title = "年龄")
    private Integer age;

    @ExcelColumn(order = 2, title = "性别")
    private String gender;

    @ExcelColumn(order = 3,title = "绘画等级")
    private String paintingLevel;

    @ExcelColumn(order = 4, title = "是否会跳舞")
    private boolean dance;

    @ExcelColumn(order = 5, title = "考核时间", format = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime assessmentTime;

    @IgnoreColumn
    private String hobby;
}
Clone this wiki locally