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();
    }
}
相关推荐
R-sz4 小时前
导出word并且插入图片
开发语言·c#·word
wáng bēn4 小时前
【java17】使用 Word 模板导出带替换符、动态表格和二维码的文档
java·word·itextpdf
小杨爱学习zb8 小时前
如何将公式图片转换为公式格式到wps/word里面
word
干净的坏蛋8 小时前
Microsoft Word 中 .doc 和 .docx 的区别
microsoft·word
码银11 小时前
基于Java的Markdown到Word文档转换工具的实现
java·word
bing_1582 天前
Word 怎么让字变大、变粗、换颜色?
word
小码氓2 天前
Java填充Word模板
java·开发语言·spring·word
会飞的天明2 天前
Java 导出word 实现饼状图导出--可编辑数据
java·word
NingrLi2 天前
Word中字号与公式字体磅值(pt)的对应关系
word
Tomorrow'sThinker2 天前
✍️ Python 批量设置 Word 文档多级字体样式(标题/正文/名称/小节)
python·自动化·word·excel