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();
    }
}
相关推荐
才疏学浅7433 小时前
批量下载鹏程实验室数据的方法
java·开发语言·word
开开心心就好4 小时前
免费开源的网课教学屏幕画板工具
windows·eureka·计算机外设·word·excel·etcd·csdn开发云
Metaphor6921 天前
使用 Python 加密或解密 Word 文档
python·安全·word
Bnews1 天前
推荐一些好用的pdf转word软件
pdf·word
Metaphor6922 天前
使用 Python 给 Word 文档设置背景
python·word
ComPDFKit2 天前
PDF 转 Word 评测:SDK、API、在线工具效果对比与选择指南
pdf·word·pdf转word·pdf转档·pdf to word
transuperb2 天前
WPS-word画出完美的三线表
word·写作·wps
黑咩狗夜.cm4 天前
(aspose.words .net)内容分别固定在一行左右俩端
c#·word·.net
E_ICEBLUE4 天前
如何提取 Word 文档中的表格并导出为 Excel(Python 教程)
python·word·excel
IT策士4 天前
Python Word操作:从入门到精通
python·c#·word