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();
    }
}
相关推荐
骆驼爱记录11 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
2301_8169978811 天前
Word 清除格式的方法
word
微光feng12 天前
毕业论文word引用操作汇总
word·目录·公式·毕业论文·交叉引用·题注
2301_8169978812 天前
Word 功能区与快速访问工具栏
word
halen33312 天前
Hellowordl: The Masters Tool for Word Puzzle Enthusiasts
word
lpfasd12312 天前
Markdown 导出 Word 文档技术方案
开发语言·c#·word
Cxiaomu12 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
bu_shuo12 天前
Word中插入文本内容控件并交叉引用
word·内容控件
缺点内向12 天前
C#中如何创建目录(TOC):使用Spire.Doc for .NET实现Word TOC自动化
c#·自动化·word·.net
2301_8169978812 天前
Word 创建打开与保存文档
c#·word·xhtml