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();
    }
}
相关推荐
Metaphor6926 小时前
使用 Python 在 Word 文档中添加、修改和删除变量
python·word
Monte053911 小时前
word 如何让mathtype公式居中,公式编号右对齐
word
2501_9307077812 小时前
如何使用C#代码替换 Word 文档中的文本
word
Metaphor6921 天前
轻松使用 Python 将 RTF 转换为 Word(含批量转换与格式互转)
python·word·rtf
IHaveADiscovery1 天前
AI代劳Word表格线条:先搞懂术语再动手
人工智能·word
徐小夕@趣谈前端1 天前
老旧Word格式全支持!JitWord协同AI文档4.1,让Word文档无缝迁移到Web端
前端·人工智能·word
ms365copilot2 天前
Copilot 代理开始进入Word、Excel、PowerPoint,不再只是“问一句答一句”
word·excel·copilot
Logic1012 天前
Excel信息+照片文件夹,自动合成word格式化文档
word·excel·办公自动化·邮件合并·office技巧·自动插入图片·插入域
万化冥合3 天前
怎么批量把 Word 转 PDF?
python·pdf·c#·word
十碗饭吃不饱3 天前
Apache POI 踩坑:setFontFamily 二次设置字体不生效、样式残留问题深度解析
java·word·apache