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();
    }
}
相关推荐
农村小镇哥2 天前
怎么把HTM格式转化成WORD
ui·c#·word
AC赳赳老秦2 天前
网页公开附件自动采集:OpenClaw 批量下载页面内嵌 Word/Excel 附件,统一格式后结构化入库
java·python·word·php·excel·deepseek·openclaw
asdzx673 天前
Java 实战:基于 Spire.Doc 高效提取 Word 文档文本与图片
java·c#·word
VBAMatrix3 天前
表格导航!实现Word合并附注与多个Excel的数据同步
word·excel·审计报告·审计·会计师事务所·报告工具
塞纳河畔的歌3 天前
保姆级教程 | Windows 安装适配 Word 的字体
word
DS随心转小程序4 天前
文心文字怎么转为 word?告别繁琐排版操作,AI 导出鸭一站式完成文档转换工作
人工智能·word·豆包·deepseek·ai导出鸭
AI导出鸭4 天前
怎么让千问做表格?AI导出鸭苹果版将千问输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭
zyplayer-doc4 天前
zyplayer-doc企业知识库能做什么:从文档创建、权限管理到AI问答的完整能力
大数据·javascript·数据库·人工智能·pdf·word
zyplayer-doc6 天前
企业文档改错或误删后怎么办:zyplayer-doc编辑历史、版本回滚和回收站怎么用
大数据·开发语言·javascript·数据库·pdf·word
Ai-_Man7 天前
豆包智能体内容批量导出:哪些该存、存成什么、怎么存v
人工智能·ai·小程序·word