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();
    }
}
相关推荐
清纯世纪1 天前
word设置的正文样式,按回车后变成了样式格式
word
ELI_He9991 天前
WPS制作论文三线表
word·论文
坚定信念,勇往无前1 天前
vue3图片,pdf,word,excel,ppt多格式文件预览组件Vue Doc Viewers Plus
pdf·word·excel
qq_296544652 天前
在怎么编辑PDF?专业级pdf转换教程,PDF在线编辑,Word转PDF使用方法
microsoft·pdf·word
jameszjd2 天前
解决WPS word主选项卡审阅栏消失问题
word·wps
fie88892 天前
Qt对Word网页的读写功能实现
开发语言·qt·word
secondyoung3 天前
WPS宏使用:一键批量调整图片与表格格式
经验分享·word·lua·markdown·wps·vb
m5655bj3 天前
Python 将 Word 文档转换为 Markdown 格式
python·c#·word
天地一沙鸥GW3 天前
如何将Word文档中已设置好的样式复制/迁移到另一个Word中??
word
qq_296544653 天前
永久免费的PDF转word,PDFgear安卓版,mac版,win版都有,word转PDF,PDF转Excel
pdf·word