Java 替换 Word 模板并插入图片
1. 前言
在实际开发中,我们经常会遇到需要根据模板生成 Word 文档并插入图片的需求。Java 提供了强大的 Apache POI 库来操作 Word 文档,本文将介绍如何使用 Java 替换 Word 模板并插入图片。
2. 准备工作
在开始之前,我们需要准备以下环境和工具:
- JDK:确保已经安装 Java 开发环境。
- Apache POI:将 Apache POI 库添加到项目中,可以通过 Maven 或手动下载添加。
3. 替换 Word 模板
首先,我们需要准备一个 Word 模板文件,包含需要替换的占位符。假设我们的模板文件名为 template.docx,其中包含一个占位符 ${content}。我们将在 Java 代码中将其替换为具体的内容。
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordReplacementExample {
public static void main(String[] args) {
try {
// 加载模板文件
FileInputStream fis = new FileInputStream("template.docx");
XWPFDocument document = new XWPFDocument(fis);
// 替换占位符
Map<String, String> replacements = new HashMap<>();
replacements.put("${content}", "这是替换后的内容");
replacePlaceholder(document, replacements);
// 保存替换后的文档
FileOutputStream fos = new FileOutputStream("output.docx");
document.write(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void replacePlaceholder(XWPFDocument document, Map<String, String> replacements) {
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : replacements.entrySet()) {
text = text.replace(entry.getKey(), entry.getValue());
}
run.setText(text, 0);
}
}
}
}
}
上面的代码演示了如何加载 Word 模板文件 template.docx,将占位符 ${content} 替换为指定的内容,并保存为新的 Word 文档 output.docx。
4. 插入图片
除了替换文本内容,我们还可以使用 Java 在 Word 文档中插入图片。假设我们有一张名为 image.jpg 的图片,我们将在模板中插入这张图片。
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordImageInsertionExample {
public static void main(String[] args) {
try {
// 加载模板文件
FileInputStream fis = new FileInputStream("template.docx");
XWPFDocument document = new XWPFDocument(fis);
// 插入图片
String imagePath = "image.jpg";
insertImage(document, imagePath);
// 保存插入图片后的文档
FileOutputStream fos = new FileOutputStream("output.docx");
document.write(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void insertImage(XWPFDocument document, String imagePath) throws IOException {
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
int format = XWPFDocument.PICTURE_TYPE_JPEG;
run.addPicture(new FileInputStream(imagePath), format, imagePath, Units.toEMU(200), Units.toEMU(200));
}
}
上面的代码演示了如何加载 Word 模板文件 template.docx,插入一张名为 image.jpg 的图片,并保存为新的 Word 文档 output.docx。在代码中,我们使用 XWPFRun 的 addPicture 方法来插入图片,并指定图片的格式和大小。
5. 总结
本文介绍了如何使用 Java 替换 Word 模板并插入图片。通过 Apache POI 库,我们可以轻松地操作 Word 文档,实现各种复杂的操作。希望本文对你有所帮助!
6. 关系图
erDiagram
WordTemplate ||.. WordReplacementExample
















