poi word写入图片

直接使用的百度结果,经过测试可行

1.pom增加jar

复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>

2.代码

复制代码
package pers.wwz.study.poiwordimage;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
 
import java.io.*;
 
public class WordExportImage {
    public static void main(String[] args) throws Exception {
        // 模板文件路径
        String templatePath = "template.docx";
        // 输出文件路径
        String outputPath = "output.docx";
        // 图片文件路径
        String imagePath = "image.png";
 
        // 读取模板
        InputStream is = new FileInputStream(templatePath);
        XWPFDocument doc = new XWPFDocument(is);
 
        // 替换文档中的图片占位符
        for (XWPFParagraph para : doc.getParagraphs()) {
            for (XWPFRun run : para.getRuns()) {
                String text = run.getText(0);
                if (text != null && text.contains("IMAGE_PLACEHOLDER")) {
                    run.setText("", 0); // 清除占位符文本
                    run.addPicture(new FileInputStream(imagePath),
                            XWPFDocument.PICTURE_TYPE_PNG, imagePath,
                            Units.toEMU(200), Units.toEMU(200)); // 插入图片
                }
            }
        }
 
        // 输出文件
        FileOutputStream out = new FileOutputStream(outputPath);
        doc.write(out);
        out.close();
        doc.close();
        is.close();
    }
}
相关推荐
玩泥巴的18 小时前
.NET驾驭Word之力:COM组件二次开发全攻略之连接Word与创建你的第一个自动化文档
word·二次开发·com互操作
辣香牛肉面2 天前
[Windows] 搜索文本2.6.2(从word、wps、excel、pdf和txt文件中查找文本的工具)
word·excel·wps·搜索文本
FlYFlOWERANDLEAF3 天前
DevExpress中Word Processing Document API学习记录
学习·c#·word
AnySpaceOne3 天前
PDF转Word在线转换教程:多种实用方法分享
学习·pdf·word
我命由我123454 天前
Word - Word 的 5 种视图(页面视图、阅读视图、Web 版式视图、大纲视图、草稿视图)
ui·word·excel·photoshop·表格·ps·美工
XYZLHL4 天前
Word怎么设置页码总页数不包含封面和目录页
word
传而习乎4 天前
Word添加图/表题注
word
YAY_tyy4 天前
基于 Vue3 + VueOffice 的多格式文档预览组件实现(支持 PDF/Word/Excel/PPT)
前端·javascript·vue.js·pdf·word·excel
东风西巷5 天前
Atlantis Word Processor:全方位的文字处理专家
前端·学习·word·软件需求