可参照着两个文档

http://deepoove.com/poi-tl/#hack-loop-table

https://www.cnblogs.com/privateLogs/p/17666702.html

字符占位符:{{}}

数组占位符:{{list}}需指定循环策略  HackLoopTableRenderPolicy,属性用[]

image

 

@GetMapping("/exportWord")
    public void exportWord() {
        Map<String,Object> map = new HashMap<>();
        GlobalTableVO vo = new GlobalTableVO();
        vo.setTitle("信息统计");
        List<WorkUser> list = workUserMapper.selectList(new LambdaQueryWrapper<WorkUser>().orderByDesc(WorkUser::getId).last(" limit 10 "));
        vo.setAllCount("总人数为:");
        vo.setCount(String.valueOf(list.size()));
        List<WorkUserVo> lst = new ArrayList<>();
        list.forEach(x -> {
            WorkUserVo workUserVo = new WorkUserVo();
            workUserVo.setCard(x.getWorkUserSole());
            workUserVo.setName(x.getWorkUserName());
            workUserVo.setPhone(x.getWorkUserTel());
            lst.add(workUserVo);
        });
        vo.setList(lst);
        map.put("title",vo.getTitle());
        map.put("allCount",vo.getAllCount());
        map.put("count",vo.getCount());
        map.put("list",vo.getList());
    
        String templatePath = "C:\\Users\\13691\\Desktop\\a.docx";
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        //绑定list
        Configure config = Configure.builder().bind("list", policy).build();
        XWPFTemplate template = XWPFTemplate.compile(templatePath,config).render(vo);
        String outputPath = "d:/profile/output.docx";
        try (FileOutputStream out = new FileOutputStream(new File(outputPath))) {
            template.write(out);
        }catch (Exception e){
            log.error("导出word文档失败,outputPath:{}",outputPath,e);
        }
        System.out.println("Word导出完成: " + outputPath);
    }

  效果图

image

 遇到的坑:poi-tl 和 若依框架自带的poi版本不兼容,4.1.x版本需要用1.10.0不能用1.12.x版本。否则会报错:org.apache.poi.xwpf.usermodel.XWPFRun.getFontSizeAsDouble()Ljava/lang/Double

<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>