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();
    }
}
相关推荐
copilot中国版4 小时前
Word Copilot|一键提取文档关键信息,告别逐字阅读
word·copilot
天人合一peng2 天前
西北工业大学校外访问系统
word
古少侠2 天前
deepseek转word工具怎么选?DS随心转与4种方案对比实测
人工智能·word·powerpoint
小羊没烦恼!3 天前
Memory 记忆设计讨论:Agent Memory 的安全边界:权限、删除、版本与回执
java·大数据·word·powerpoint·.net
拆房老料3 天前
BaseMetas FileView 1.3.0 发布:大文件更稳,PDF 预览更完整
pdf·word·开源软件·ppt
weixin_416660073 天前
DeepSeek、豆包生成的表格怎么导出Excel,避免内容挤在一列?
word·豆包·deepseek
鲲穹AI种草5 天前
Word 文稿批量规范化处理,多款 Word 批量处理工具能力客观记录
word·批量处理·页面页脚
SunnyDays10116 天前
使用 Python 提取 Word 文档中的表格数据
python·word
weixin_416660076 天前
DeepSeek生成的数学公式怎么导出到Word并保持可编辑?
word·deepseek
蝶恋舞者6 天前
Word 实现「图 X」序号自动递增 和交叉引用
word