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();
    }
}
相关推荐
wtsolutions8 小时前
Sheet-to-Doc Skill: Let AI Assistants Generate Word Documents for You
人工智能·word
qq_466302452 天前
如何在word中添加代码
word
一棵星2 天前
LibreOffice Word 转 PDF 报错 “source file could not be loaded” 完整解决方案
pdf·word
一棵星3 天前
记一次 Word 转 PDF 功能故障排查与修复
pdf·word
拆房老料4 天前
ONLYOFFICE AI Agent 深度解析:在线 Office 正从编辑器走向智能工作平台
人工智能·中间件·编辑器·word·开源软件
186******205315 天前
PDF 转 Word 高效办公实战指南
pdf·word
patrickpdx6 天前
Word批量修改指定字符的字体
word·word2016
asdzx677 天前
使用 Spire.WordJS 在 React 中实现在线 Word 文档编辑
前端·react.js·word
速易达网络7 天前
在线web文本图片绘图系统
word
zavoryn8 天前
Word 图片如何进入 RAG:Apache POI、MinIO 与 URL 映射
word·agent·rag