Java 读取 Word 模板文档并替换内容生成新文档

嘿,朋友们!在实际开发中,经常会遇到需要根据 Word 模板生成特定文档的需求,比如合同、报告等。咱们可以使用 Apache POI 库来读取 Word 模板文档,然后替换其中的指定内容,最后生成新的文档。下面我就详细给大家讲讲具体怎么做。

1. 引入依赖

如果你使用的是 Maven 项目,在 pom.xml 中添加以下依赖:

复制代码
XML 复制代码
<dependencies>
    <!-- Apache POI 处理 Word 文档 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
</dependencies>

2. 创建 Word 模板

首先,创建一个 Word 模板文件 template.docx,在模板中使用特定的占位符来表示需要替换的内容,例如 {name}{date} 等。假设模板内容如下:

复制代码
XML 复制代码
这是一份测试文档。
姓名:{name}
日期:{date}

3. Java 代码实现

复制代码
java 复制代码
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WordTemplateProcessor {
    public static void main(String[] args) {
        try {
            // 读取 Word 模板文件
            FileInputStream fis = new FileInputStream("template.docx");
            XWPFDocument document = new XWPFDocument(fis);

            // 准备要替换的数据
            Map<String, String> data = new HashMap<>();
            data.put("{name}", "张三");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            data.put("{date}", sdf.format(new Date()));

            // 替换文档中的占位符
            replacePlaceholders(document, data);

            // 保存为新的 Word 文档
            FileOutputStream fos = new FileOutputStream("output.docx");
            document.write(fos);
            fos.close();
            fis.close();

            System.out.println("新的 Word 文档生成成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("生成新的 Word 文档失败:" + e.getMessage());
        }
    }

    private static void replacePlaceholders(XWPFDocument document, Map<String, String> data) {
        // 遍历文档中的每个段落
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            // 遍历段落中的每个文本运行对象
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null) {
                    // 遍历数据映射,替换占位符
                    for (Map.Entry<String, String> entry : data.entrySet()) {
                        String placeholder = entry.getKey();
                        String replacement = entry.getValue();
                        if (text.contains(placeholder)) {
                            text = text.replace(placeholder, replacement);
                            run.setText(text, 0);
                        }
                    }
                }
            }
        }
    }
}

4. 代码解释

读取 Word 模板文件

复制代码
java 复制代码
FileInputStream fis = new FileInputStream("template.docx");
XWPFDocument document = new XWPFDocument(fis);

通过 FileInputStream 读取 template.docx 文件,然后使用 XWPFDocument 类将其加载到内存中。

准备要替换的数据

复制代码
java 复制代码
Map<String, String> data = new HashMap<>();
data.put("{name}", "张三");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
data.put("{date}", sdf.format(new Date()));

创建一个 Map 对象,将占位符和要替换的内容进行映射。

替换文档中的占位符

复制代码
java 复制代码
private static void replacePlaceholders(XWPFDocument document, Map<String, String> data) {
    for (XWPFParagraph paragraph : document.getParagraphs()) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                for (Map.Entry<String, String> entry : data.entrySet()) {
                    String placeholder = entry.getKey();
                    String replacement = entry.getValue();
                    if (text.contains(placeholder)) {
                        text = text.replace(placeholder, replacement);
                        run.setText(text, 0);
                    }
                }
            }
        }
    }
}

遍历文档中的每个段落和文本运行对象,检查文本中是否包含占位符,如果包含则进行替换。

保存为新的 Word 文档

复制代码
java 复制代码
FileOutputStream fos = new FileOutputStream("output.docx");
document.write(fos);
fos.close();
fis.close();

使用 FileOutputStream 将替换后的文档保存为 output.docx 文件。

嘿,朋友们!按照上面的步骤,你就可以使用 Java 读取 Word 模板文档并替换指定内容,生成新的文档啦。赶紧动手试试吧!

相关推荐
Q_970956395 分钟前
java+vue+SpringBoo校园失物招领网站(程序+数据库+报告+部署教程+答辩指导)
java·数据库·vue.js
Wyc7240913 分钟前
Maven
java·数据库·maven
军训猫猫头15 分钟前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
程序猿小D16 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的电影小说网站管理系统,推荐!
java·数据库·mysql·spring·毕业设计·ssm框架·电影小说网站
真的想上岸啊29 分钟前
学习C++、QT---18(C++ 记事本项目的stylesheet)
开发语言·c++·学习
明天好,会的35 分钟前
跨平台ZeroMQ:在Rust中使用zmq库的完整指南
开发语言·后端·rust
丁劲犇1 小时前
用 Turbo Vision 2 为 Qt 6 控制台应用创建 TUI 字符 MainFrame
开发语言·c++·qt·tui·字符界面·curse
旷世奇才李先生2 小时前
Next.js 安装使用教程
开发语言·javascript·ecmascript
木头没有瓜2 小时前
idea离线安装插件
java·ide·intellij-idea
llwszx2 小时前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务