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();
    }
}
相关推荐
2501_930707786 小时前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
weixin_416660071 天前
AI 生成的 Mermaid 流程图和 LaTeX 公式,怎么一起导出到 Word?
人工智能·word·流程图·豆包
asdzx671 天前
使用 Python 按页或节拆分 Word 文档
python·word
死磕音视频1 天前
Microsoft Copilot 办公入门:在 Word、Excel、PowerPoint 里用 AI 完成日常文档工作
word·excel·copilot·办公效率
2501_930707781 天前
如何使用C#代码合并Word文档
word
芦芭荞2 天前
QT使用xml模版生成word文档
xml·qt·word
Am-Chestnuts2 天前
DeepSeek写教案怎么导出Word?完整步骤
ai·word
jun_bai3 天前
使用Aspose实现word文档合并,内容替换
windows·c#·word
开开心心就好3 天前
把手机变成电脑麦克风,WiFi连接就能用
智能手机·ffmpeg·计算机外设·电脑·word·音视频
言乐63 天前
HTML实现Word、Excel、PPT三种可切换背景,可键盘打字、和像素小人交互
html·word·powerpoint·excel·交互