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();
    }
}
相关推荐
圣光SG14 小时前
Word 综合实操项目:标准求职简历制作
word
RisunJan18 小时前
项目经理面试知识点梳理
面试·职场和发展·word
拆房老料18 小时前
LibreOffice 26.8 发布后,再看 BaseMetas FileView 的 Office 转 PDF 技术路线
pdf·word·开源软件·ppt·格式工厂
统计学小王子2 天前
数学建模国赛倒计时8天——《搭建建模Word框架(字体字号)》
数学建模·word
EXI-小洲4 天前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
三声三视5 天前
Word 转 Markdown 报“保真率 98%“,可那张表散了
word·word转markdown·格式转换·开发者工具·tri-docx2md·结构保真
课件帮5 天前
从Word教案到带讲解微课:课件帮一键成片全流程实操
word
2601_949950635 天前
Word、PDF、Excel题目怎么快速整理?
pdf·word·excel
百事牛科技5 天前
文档不想再加密了?Word打开密码移除的两种方法
windows·word
redfred5 天前
Stirling-PDF 使用教程:开源 PDF 工具箱 50+ 工具 PDF转Word/合并/压缩/OCR 桌面版 Docker 部署详解
pdf·开源·word