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();
    }
}
相关推荐
小羊没烦恼!3 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
Am-Chestnuts3 天前
DeepSeek表格复制到Word变竖线错列?用DS随心转对比几种整理方法
人工智能·word·ds随心转
2501_930707786 天前
使用C#代码为新创建的 Word 文档创建目录
c#·word
SunnyDays10116 天前
Java 拆分 Word 文档教程:按页、分页符和分节符拆分
java·word·分页·拆分
copilot中国版7 天前
Word Copilot|一键提取文档关键信息,告别逐字阅读
word·copilot
天人合一peng9 天前
西北工业大学校外访问系统
word
古少侠9 天前
deepseek转word工具怎么选?DS随心转与4种方案对比实测
人工智能·word·powerpoint
小羊没烦恼!10 天前
Memory 记忆设计讨论:Agent Memory 的安全边界:权限、删除、版本与回执
java·大数据·word·powerpoint·.net
拆房老料10 天前
BaseMetas FileView 1.3.0 发布:大文件更稳,PDF 预览更完整
pdf·word·开源软件·ppt
weixin_4166600710 天前
DeepSeek、豆包生成的表格怎么导出Excel,避免内容挤在一列?
word·豆包·deepseek