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();
    }
}
相关推荐
2601_9659129114 小时前
PDF转Word工具深度横评:2026年国内免费方案技术对比
pdf·word
L歪歪君 山水甲天15 小时前
Office文件的奥秘——.NET平台下不借助Office实现Word、Powerpoint等文件的解析(1)
word·powerpoint·.net
SpaceAIGlobal19 小时前
Word文档一键转PPT?4种方法实测对比与选型分析(2026)
word·powerpoint
随手工具-Excel, pdf, SQL2 天前
多个 PDF 怎么合并成一个?免费在线工具,还能混入图片和 Word
pdf·word·效率工具·在线工具·pdf合并·合并pdf
ms365copilot2 天前
在Copilot聊天中添加Word、Excel 和 PowerPoint 代理
word·excel·copilot
2601_965912832 天前
PDF转Word技术选型:2026年文档解析引擎性能对比与集成评估
pdf·word
大数据张老师2 天前
Typora 导出 Word 模版操作手册
开发语言·c#·word·typora
DS随心转小程序4 天前
实测评测 AI 导出鸭转化效能,全方位优化 DeepSeek 输出 word 文档落地使用效率
人工智能·aigc·word·豆包·deepseek·ai导出鸭
AI导出鸭PC端4 天前
AI 导出鸭一站式转换工具,ChatGPT 内容怎么生成 word 无需手动复制排版
人工智能·chatgpt·word·豆包·ai导出鸭
开开心心就好5 天前
批量图片OCR识别重命名工具完全免费
随机森林·智能手机·ocr·电脑·word·音视频·最小二乘法