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();
    }
}
相关推荐
DS随心转插件6 小时前
AI导出鸭:DeepSeek 转 Word 效果实测与案例展示
人工智能·ai·word·豆包·deepseek·ai导出鸭
itgather10 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
DS随心转插件11 小时前
AI导出鸭深度评测:DeepSeek 转 Word 实战表现与边界分析
人工智能·ai·word·文心一言·deepseek·ai导出鸭
qq_422152571 天前
PDF 转 Word 哪个工具好用?2026 年主流方案对比与选型指南
pdf·word
AI导出鸭PC端1 天前
智谱清言怎么生成word文档?AI导出鸭终结乱码烦恼
人工智能·ai·c#·word·豆包·ai导出鸭
asdzx671 天前
使用 Python 精准提取 Word 文档中的文本与表格
python·word
齐齐大魔王1 天前
Word缩放打印功能
word
AI导出鸭PC端2 天前
智谱清言怎样生成word文档——AI导出鸭助您一键转文档
人工智能·ai·word·豆包·deepseek·ai导出鸭
小桥流水---人工智能2 天前
Word/WPS中英文连字符(断字)问题的三种解决方法
word·wps
likerhood3 天前
Word 两列文档中插入横跨两列的表格
word