java通过模板生成word文档

工具库:https://github.com/Sayi/poi-tl

中文文档:http://deepoove.com/poi-tl/

pom依赖

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.7.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

示例参考:https://blog.csdn.net/qq_41532872/article/details/108644773

注意windows环境下的路径问题,使用/作为路径分隔符

【示例】

渲染普通文本

public static void main(String[] args) throws IOException {
    Map<String, Object> data = new HashMap<>();
    data.put("title", "司天宏");
    XWPFTemplate template = XWPFTemplate.compile("D:/basis_platform_core/weather/src/main/resources/template.docx")
        .render(data);
    FileOutputStream out;
    out = new FileOutputStream("D:/basis_platform_core/weather/src/main/resources/template2.docx");
    template.write(out);
    out.flush();
    out.close();
    template.close();
}

渲染图片

public static void main(String[] args) throws IOException {
    Map<String, Object> data = new HashMap<>();
    // 本地图片
    data.put("local", new PictureRenderData(80, 100, "C:/Users/shen_/Pictures/dir.png"));

    // 图片流
    // data.put("localbyte", new PictureRenderData(80, 100, ".png", new FileInputStream("./logo.png")));

    // 网络图片(注意网络耗时对系统可能的性能影响)
    // data.put("urlpicture", new PictureRenderData(50, 50, ".png", BytePictureUtils.getUrlBufferedImage("http://deepoove.com/images/icecream.png")));

    // java 图片
    //data.put("bufferimage", new PictureRenderData(80, 100, ".png", bufferImage)));
    XWPFTemplate template = XWPFTemplate.compile("D:/jtzl-myworkspace/code/basis_platform_core/weather/src/main/resources/template.docx")
            .render(data);
    FileOutputStream out;
    out = new FileOutputStream("D:/jtzl-myworkspace/code/basis_platform_core/weather/src/main/resources/template2.docx");
    template.write(out);
    out.flush();
    out.close();
    template.close();
}
posted @ 2022-08-24 10:48  黄河大道东  阅读(175)  评论(0编辑  收藏  举报