XWPFTemplate(二)动态生成表格

复制代码
记录XWPFTemplate关于表格的遍历。

具体代码

java 复制代码
public static void main(String[] args) throws IOException {
        //模板文件地址
        String filePath = "/Users/liu/Downloads/test.docx";

        Map<String,Object> map = new HashMap<>();
        Calendar now = Calendar.getInstance();
        //年
        map.put("year", now.get(Calendar.YEAR));
        //月
        map.put("month", (now.get(Calendar.MONTH)) + 1);
        //日
        map.put("day", now.get(Calendar.DAY_OF_MONTH));

        List<Map<String,Object>> detailList=new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String,Object> detailMap = new HashMap<>();
            detailMap.put("key",i);
            detailMap.put("key1","name"+i);
            detailMap.put("key2",i+"kg");
            detailMap.put("key3",i);
            detailMap.put("key4",103.3);
            detailList.add(detailMap);
        }
        //图片
        InputStream png = new FileInputStream("/Users/liu/Pictures/表情/7301626317522_.pic_hd.jpg");
        map.put("png", new PictureRenderData(270, 270, PictureType.PNG, png));
        List<HashMap> arrayList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            HashMap m = new HashMap();
            m.put("image", Pictures.ofStream(new FileInputStream("/Users/liu/Pictures/表情/7301626317522_.pic_hd.jpg"), PictureType.PNG)
                    .size(400, 400).create());
            arrayList.add(m);
        }
        map.put("images",arrayList);
        //渲染表格
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        ConfigureBuilder configureBuilder = Configure.builder();
        configureBuilder.bind("details", policy);
        Configure config = configureBuilder.build();
        map.put("details", detailList);
        map.put("title","测试生成");//总金额

        XWPFTemplate template = XWPFTemplate.compile(filePath, config).render(map);

        File file = new File("/Users/liu/Downloads/test1.docx");
        FileOutputStream out = new FileOutputStream(file);
        template.write(out);
        out.close();
    }

模板文件

生成效果

相关推荐
lang201509282 小时前
深入掌握 Maven Settings:从配置到实战
java·maven
scx_link2 小时前
修改JetBrains产品(IntelliJ IDEA 、PyCharm等软件)的默认插件和日志的存储位置
java·pycharm·intellij-idea
BUG?不,是彩蛋!2 小时前
Maven-Java 项目到底解决了什么痛点?
java·servlet·maven
小池先生2 小时前
idea配置代码注释模板
java·ide·intellij-idea
inferno2 小时前
Maven基础(一)
java·开发语言·maven
摇滚侠2 小时前
Spring Boot3零基础教程,Reactive-Stream 规范核心接口,笔记103
java·spring boot·笔记
程序猿小蒜3 小时前
基于springboot的校园社团信息管理系统开发与设计
java·前端·spring boot·后端·spring
兔兔爱学习兔兔爱学习3 小时前
Spring Al学习9:模型上下文协议(MCP)
java·学习·spring
m0_748248023 小时前
Spring MVC中@RequestMapping注解的全面解析
java·spring·mvc
Mos_x3 小时前
28.<Spring博客系统⑤(部署的整个过程
java·后端