Java Poi-tl操作Word文档,插入文本和图片

    科技2022-07-13  120

    前言:poi-tl(poi template language)是Word模板引擎,基于Microsoft Word模板和数据生成新的文档。详细使用见:官方文档

    1、pom.xml引入依赖

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

    2、准备Word模板【自我介绍.docx】 文本标签: {{ }} 图片标签:以@开始:{{@var}}

    3、主要代码

    import java.io.File; import java.util.Map; import java.util.HashMap; import java.io.FileOutputStream; import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.util.BytePictureUtils; import com.deepoove.poi.data.PictureRenderData; public class Application { public static void main(String[] args) throws Exception { Map<String, Object> map = new HashMap<>(); map.put("name", "tony"); map.put("age", "18"); // 读取本地磁盘图片 map.put("weChatPicture", new PictureRenderData(100, 100, "D:\\weChat.jpg")); // 通过url读取网络图片 map.put("picture", new PictureRenderData(200, 400, ".png", BytePictureUtils.getUrlByteArray("https://res.wx.qq.com/a/wx_fed/weixin_portal/res/static/img/1EtCRvm.png"))); File file = new File("D:\\自我介绍.docx"); XWPFTemplate template = XWPFTemplate.compile(file).render(map); FileOutputStream out = new FileOutputStream(new File("D:\\输出自我介绍.docx")); template.write(out); out.flush(); out.close(); template.close(); } }

    4、效果图【输出自我介绍.docx】

    Processed: 0.011, SQL: 8