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();
    }
}
相关推荐
逐渐会飞1 天前
如何用python在word插入复选框
python·word
AndrewMe82112 天前
detailed-docx:一个能保住格式的 Word 文档操作库
开发语言·python·word
热爱生活的五柒2 天前
如何自动更新zotero?正文调换章节顺序后参考文献错乱无法刷新怎么办?
word·zotero·参考文献
骆驼爱记录3 天前
Word一键批量添加图章
自动化·word·excel·wps·新人首发
码路星河3 天前
SpringBoot3实战:优雅实现Word文档动态生成与下载
开发语言·c#·word
Eiceblue3 天前
通过 C# 读取 Word 表格数据:高效解析 + 导出为 CSV/TXT
开发语言·c#·word
育种数据分析之放飞自我4 天前
obsidian的md文件导出word文件插件:Docx Exporter
word
进击的女IT4 天前
Java使用poi-tl实现word模版渲染文本/图片
java·数据库·word
A Everyman5 天前
Java 高效生成 Word 文档:poi-tl 的使用
java·pdf·word·poi-tl
AI英德西牛仔5 天前
ChatGPT和Gemini导出word排版
人工智能·ai·chatgpt·word·deepseek·ds随心转