使用poi-tl循环导出word报表

先看模板和导出的效果
模板
使用poi-tl循环导出word报表_第1张图片
效果
使用poi-tl循环导出word报表_第2张图片
根据模板循环生成表格,每个表格再循环填充数据,也就是两层循环,第一层循环是学生学期信息,第二层循环是学生的成绩数据。

第一个循环

{{?listTable}} 
{{/}}

第二个循环

{{reportList}}
表格中[]是具体的属性,比如[displayName]表示课程名称

核心代码

maven

<dependency>
    <groupId>com.deepoovegroupId>
    <artifactId>poi-tlartifactId>
    <version>1.10.5version>
dependency>
@Test
public void export() throws IOException {

    // 模板文件
    ClassPathResource classPathResource = new ClassPathResource("/doc/template.docx");
    InputStream inputStream = classPathResource.getInputStream();

    Map<String, Object> map = new HashMap<>();

    String str = FileUtil.readFileByPath("C:\\Users\\chenggaowei\\Desktop\\score.json");

    List<StudentCourseVO> studentList = new ArrayList<>();
    // 模拟写入多个学生的数据
    for (int i = 0; i < 3; i++) {

        StudentCourseVO vo = new StudentCourseVO();

        vo.setStudentName("张三" + (i + 1));
        vo.setPeriodName("2023-2024学年上学期");

        List<ReportField> reportList = JSONObject.parseArray(str, ReportField.class);
        vo.setReportList(reportList);

        studentList.add(vo);
    }
    // 循环的数据,listTable和模板对应
    map.put("listTable", studentList);

    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
    // reportList和模板对应
    Configure config = Configure.builder().bind("reportList", policy).build();
    XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(map);

    File outputFile = FileUtil.createTempFile("out.docx");
    template.writeToFile(outputFile.getAbsolutePath());

    FileUtil.openFolder(outputFile);

}

学业课程数据vo


/**
 * 学业课程数据
 * @author chenggaowei
 * @date 2023/10/8
 */
@Data
public class StudentCourseVO {
    /**
     * 学生id
     */
    private String studentId;
    /**
     * 学生姓名
     */
    private String studentName;
    /**
     * 学期id
     */
    private String periodId;
    /**
     * 学期名称
     */
    private String periodName;
    /**
     * 成绩数据
     */
    private List<ReportField> reportList;
}

你可能感兴趣的:(word报表,word)