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();
    }
}
相关推荐
白狐_7988 小时前
【疑难杂症】Word 惊现“数字 7 消失术”:特定字体 GBK 编码下的渲染陷阱排查
word
热爱生活的五柒1 天前
为什么word里面没有墨迹公式,从哪找
word
yivifu2 天前
使用VBA区分简体中文段落和繁体中文段落的方法
word·excel·vba
骆驼爱记录2 天前
Word三线表制作全攻略
自动化·word·wps·新人首发
盘古工具3 天前
告别重复劳动:Word 重复上一次操作的两种方法
windows·word
好名字08214 天前
Vue2转Word方法(html-docx-js库)
javascript·html·word
檐下翻书1734 天前
企业组织架构图导出Word 在线编辑免费工具
人工智能·信息可视化·去中心化·word·流程图·ai编程
涛涛北京4 天前
【word】- 宏操作 - 如何在word中插入宏
word
涛涛北京4 天前
【word】- 宏操作 - 如何在word中批量修改图片格式
word
usdoc文档预览4 天前
Word文件转PDF、WPS在线打印、js提取Word文件内容、轻松将Word文档转为PDF
pdf·word·wps·在线预览·word转pdf·在线编辑·ofd在线预览解析