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();
    }
}
相关推荐
zavoryn14 小时前
Word 图片如何进入 RAG:Apache POI、MinIO 与 URL 映射
word·agent·rag
AI导出鸭PC端14 小时前
预览即导出:告别AI文档格式崩塌,网页预览效果1:1落地Word
人工智能·pdf·word·流程图·豆包·ai导出鸭
asdzx671 天前
使用 Python 精准操控 Word 字体:获取与替换方案
python·c#·word
Am-Chestnuts1 天前
Mermaid流程图怎么导出Word/PDF?DS随心转批量保存AI多轮修改与源码
pdf·aigc·word·流程图
DS随心转小程序2 天前
deepseek 生成 word 文档指令搭配 AI 导出鸭高效完成各类文档批量输出
人工智能·word·豆包·deepseek·ai导出鸭
java_logo2 天前
Docker 部署 WPS 在线办公套件,浏览器即可编辑 Word、Excel、PPT
docker·word·wps·wps部署教程·wps免费版·轩辕镜像·docker部署教程
wtsolutions2 天前
Word 文档 怎么批量加密 批量设置打开密码
word·加密
不坑老师4 天前
怎么在Word中制作汉字书写笔顺——不坑盒子汉字笔顺步骤在小学低段识字教学中的应用
前端·数据库·人工智能·word·excel·office
2601_963771374 天前
Hardening Enterprise WordPress Sites Against REST API Leaks and Bad Headers
前端·windows·word·php
_清风来叙5 天前
【软件】Word软件不支持显示emoji表情包如何解决
电脑·word