天天看點

Java操作word模闆插入圖檔

Java操作word模闆插入圖檔

1.制作word模闆,插入圖檔使用文法@,支援插入本地圖檔和網絡圖檔

{{@localPicture}}

{{@urlPicture}}

2.使用Poi-tl,添加依賴

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

3.Java代碼示例

public void testNumbericRender() throws Exception {
        Map<String, Object> datas = new HashMap<String, Object>() {
            {
                //本地圖檔
                put("localPicture", new PictureRenderData(100, 120, "src/test/resources/logo.png"));
                //網路圖檔 
                put("urlPicture", new PictureRenderData(100, 100, ".png", BytePictureUtils.getUrlByteArray("https://avatars3.githubusercontent.com/u/1394854?v=3&s=40")));
            }
        };

        XWPFTemplate template = XWPFTemplate.compile("~/picture.docx")
                .render(datas);

        FileOutputStream out = new FileOutputStream("out_picture.docx");
        template.write(out);
        out.flush();
        out.close();
        template.close();
    }