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();
    }
}
相关推荐
Tmin.2 天前
Word论文中遇到的
word
智航GIS2 天前
9.4 Word 自动化
python·自动化·word
深念Y3 天前
学习通下载老师没有开放下载的文档的方法
学习·pdf·word·文档·下载·学习通·开发者模式
开开心心_Every3 天前
提取PPT/Word/Excel图片工具
数据库·微信·pdf·word·powerpoint·excel·语音识别
蜡笔小鑫jolly4 天前
在WORD中插入表格后放图片一直不吻合怎么办?
word
YuQiao03034 天前
华科学位论文——驯服word公式编辑器(不是mathtype的)
编辑器·word
YuQiao03034 天前
华科学位论文——驯服word之 目录
word
重生之光头强下海当程序猿4 天前
word将所选内容超链接为文章其他内容
word
SEO-狼术4 天前
Convert Word Documents to PDF
pdf·word
发际线的忧伤5 天前
Word 的一个显示模式,页眉页脚数据丢失?
word