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();
    }
}
相关推荐
qq_546937271 天前
Excel批量转PDF_Word_图片,支持自动合并报表,效率翻倍。
pdf·word·excel
(Charon)2 天前
【C++ 面试高频:内存管理、RAII 和智能指针详解】
java·开发语言·word
江畔柳前堤2 天前
github实战指南03-Pull Request 全流程实战
开发语言·人工智能·python·深度学习·github·word
2603_954138393 天前
PDF 转 Word 工具深度评测:从参数解析到实战避坑
pdf·word
知南x3 天前
【DPDK例程学习】(4) l2fwd
学习·word
江畔柳前堤3 天前
github实战指南00-命令在哪里执行?
人工智能·线性代数·oracle·数据挖掘·github·word
江畔柳前堤4 天前
github实战指南05-Fork与开源协作
人工智能·线性代数·oracle·开源·github·word
yivifu4 天前
怎样将Word文档中脚注引用后面的空格轻松删除
word·vba
Sour4 天前
Word 文档翻译后保留格式的检查清单:标题、表格、图片、目录和批注
pdf·word·办公软件·office·文档翻译
qq_422152575 天前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word