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();
    }
}
相关推荐
AI导出鸭PC端10 小时前
豆包智能体停运在即,历史对话如何一键导出为 Word 或 PDF?
人工智能·pdf·word·豆包·ai导出鸭
asdzx6717 小时前
C# 通过模板生成 Word 文档:文本与图片占位符替换完整攻略
开发语言·c#·word
Metaphor6921 天前
使用 Python 在 Word 文档中添加批注
python·word
lang201509282 天前
Apache POI Word(docx) 实战教程:从入门到精通表格合并、图片插入与文档合并
java·开发语言·word
Sour2 天前
产品说明书翻译成英文怎么保留排版?PDF、Word、外贸资料处理清单
pdf·word
AI刀刀2 天前
豆包智能体 7 月 15 日全面下线:技术解读、数据迁移与自动化备份方案
运维·人工智能·自动化·word·excel·ai导出鸭
俊哥工具2 天前
解决文件正在使用无法删除,顽固文件清理工具超好用
智能手机·电脑·word·音视频·媒体
沉默的云朵3 天前
NET平台下不借助Office实现Word、Powerpoint等文件的解析(一)
word·powerpoint
忧郁的紫菜3 天前
基础实现:单篇 Markdown 转 Word
开发语言·c#·word
chushiyunen4 天前
word使用笔记(二)、邮件合并(模板套用)
笔记·word