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();
    }

模板文件

生成效果

相关推荐
用户35218024547511 小时前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
东坡白菜14 小时前
破局全栈:一个前端开发的Java入门实战记录(1)
java·全栈
唐青枫14 小时前
Java Tomcat 实战指南:从 Servlet 容器到 Spring Boot 部署
java
wsaaaqqq14 小时前
roudan:自由选择实体、灵活操作数据、快速写入数据库的 Java 框架
java
plainGeekDev18 小时前
null 判断 → Kotlin 可空类型
android·java·kotlin
糖拌西瓜皮18 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
plainGeekDev18 小时前
getter/setter → Kotlin 属性
android·java·kotlin
一线大码18 小时前
Smart-Doc 的简单使用
java·后端·restful
MacroZheng19 小时前
Claude Code官方桌面端正式发布,夯爆了!
java·人工智能·后端