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

模板文件

生成效果

相关推荐
ytadpole10 分钟前
揭秘设计模式:命令模式-告别混乱,打造优雅可扩展的代码
java·设计模式
用户37215742613515 分钟前
Java 教程:轻松实现 Excel 与 CSV 互转 (含批量转换)
java
叫我阿柒啊43 分钟前
Java全栈开发实战:从基础到微服务的深度解析
java·微服务·kafka·vue3·springboot·jwt·前端开发
凯尔萨厮1 小时前
Java学习笔记三(封装)
java·笔记·学习
霸道流氓气质1 小时前
Java开发中常用CollectionUtils方式,以及Spring中CollectionUtils常用方法示例
java·spring
失散131 小时前
分布式专题——5 大厂Redis高并发缓存架构实战与性能优化
java·redis·分布式·缓存·架构
通达的K1 小时前
Java实战项目演示代码及流的使用
java·开发语言·windows
David爱编程1 小时前
深入 Java synchronized 底层:字节码解析与 MonitorEnter 原理全揭秘
java·后端
索迪迈科技1 小时前
Protobuf 新版“调试表示为什么有链接?为什么会打码?我该怎么改代码?
java·log4j·apache
a_blue_ice1 小时前
JAVA 面试 MySQL
java·mysql·面试