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随心转APP10 小时前
AI生成的word怎么下载?AI导出鸭技术架构深度测评
人工智能·ai·架构·word·deepseek·ai导出鸭
Am-Chestnuts10 小时前
DeepSeek复制到Word有黑底怎么办?用DS随心转保留原文再整理格式
word
Metaphor69213 小时前
使用 Python 快速在 Word 文档中插入图片
python·word
Am-Chestnuts13 小时前
AI 复制到 Word 格式乱怎么办?先保留 Markdown 再转换
word
AI刀刀18 小时前
能生成 word 文档的文心在导出时易出现排版错乱,AI 导出鸭精准优化版式,提升文档完整性
人工智能·c#·word·excel·ai导出鸭
为你奋斗!19 小时前
禅道Bug导出CSV文件批量转Word+图片离线部署操作手册
word·bug
MindUp19 小时前
Word 转 PPT 自动化实践:8 款 AI 生成工具的自然语言处理与排版效果横向评测
人工智能·word·powerpoint
reasonsummer2 天前
【办公类-109-12】20260901圆形挂牌(模版重制:文本框圆形重叠_word编辑单面_接送卡&被子卡&床卡&入园卡)
python·word
AI导出鸭2 天前
怎么让Claude做表格?AI导出鸭苹果版将Claude输出的Markdown表格或结构化列表智能解析为二维数据,一键导出Excel/Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭
AI刀刀2 天前
Kimi 文档导出格式错乱、排版丢失、导出报错?AI 导出鸭一键智能适配,稳定输出规范 Word、PDF,高效解决各类导出难题
人工智能·pdf·word·ai导出鸭