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();
    }
}
相关推荐
vancece11 小时前
新时代的 AI 教育体系 - 全开源:Word Teacher 英语口语训练
人工智能·开源·word
aaaffaewrerewrwer1 天前
一个真正可玩、可分享、可自定义的在线单词搜索游戏网站(Word Search Puzzles)
游戏·word
tedcloud1231 天前
codegraph部署教程:构建代码库语义分析环境
服务器·人工智能·word·excel
江畔柳前堤1 天前
XZ09_Word和MD格式转换
开发语言·数据库·人工智能·python·深度学习·word
yurenpai(27届找实习中)1 天前
Spring AI 实战:从零实现 AI 对话的记忆与历史记录管理(附源码级解析)
java·spring·ai·prompt·word
庖丁AI1 天前
文档比对工具怎么选?Word、PDF、扫描件差异检测思路
pdf·word·扫描件·文档比对
tedcloud1232 天前
DeepSeek-TUI部署教程:打造CLI AI助手环境
服务器·人工智能·word·excel·dreamweaver
aihuangwu2 天前
AI导出鸭|ChatGPT与Gemini生成Word文档技术实操
人工智能·ai·chatgpt·word·deepseek·ai导出鸭
_oP_i2 天前
105、word 出现 {TOCO“1-2“HZ}
开发语言·c#·word
gc_22993 天前
学习C#调用OpenXml操作word文档的基本用法(39:学习表格类-1)
c#·word·表格·table·openxml