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();
    }
}
相关推荐
蝶恋舞者14 小时前
Word怎样把题注格式保存到【开始】选项卡的样式库
word
weixin_4935036718 小时前
商会系统里的在线文件预览:PDF/Word/Excel 三种实现与选型(Node + 前端实战)
pdf·word·excel
北城笑笑20 小时前
Vue 104 ,AI + ECharts + Word:大模型数据可视化报告生成实战(前端导出图文并茂 Word 文档)
前端·vue.js·word·echarts
AIGC大时代2 天前
Obsidian × Claude Cowork × Word:把研究笔记变成可验收写作链
笔记·word·claude·学术写作·obsidian·研工作流
Am-Chestnuts2 天前
通义千问任务清单怎么导出Word?用DS随心转保留层级和勾选项
开发语言·c#·word
Am-Chestnuts2 天前
豆包、DeepSeek公式怎么导出Word?用DS随心转保留可编辑格式
word
古少侠2 天前
DeepSeek长回答怎么保存成Word?避免逐段复制和漏内容
c#·word
laoban-yu3 天前
Word与PDF文档互转
pdf·word·文档转换
古少侠3 天前
用 DS随心转 把 AI 给的表格整理成排版正常、能改的 Word
word
2601_962295333 天前
Python自动化批量文档生成工具:Word与Excel的结合应用
python·自动化·word·excel·文档生成