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();
    }
}
相关推荐
weixin_416660072 小时前
插件分享:将AI生成的数学公式无损导出为Word文档
人工智能·ai·word·论文·数学公式·deepseek
缺点内向6 小时前
C# 中如何从 URL 下载 Word 文档:基于 Spire.Doc 的高效解决方案
开发语言·c#·word
dyxal6 小时前
论文格式魔法全书:用Word通配符和宏一键完成专业排版
开发语言·word
wangbing11251 天前
将swagger在线文档转为word
microsoft·c#·word
kiki-bf2 天前
使用python把图片转为word
开发语言·python·word
开开心心_Every2 天前
Word转PDF工具,免费生成图片型文档
网络·笔记·pdf·word·powerpoint·excel·azure
dlhto2 天前
Markdown转Word操作指南
linux·centos·word
重生之光头强下海当程序猿3 天前
解决word中图像显示不全或者添加题注选项消失的问题
word
Array*3 天前
java实现word中插入附件(支持所有文件格式)
java·开发语言·word·poi·ole
艾上编程3 天前
第一章——办公自动化之Word报告自动生成:解放双手,高效创作
word