直接使用的百度结果,经过测试可行
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();
}
}