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

news/2025/2/9 5:14:03 标签: java, word, 开发语言

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

1. 引入依赖

如果你使用的是 Maven 项目,在 pom.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} 等。假设模板内容如下:

 
这是一份测试文档。
姓名:{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 模板文档并替换指定内容,生成新的文档啦。赶紧动手试试吧!


http://www.niftyadmin.cn/n/5845523.html

相关文章

计算机毕业设计SparkStreaming+Kafka广告推荐系统 广告预测 广告数据分析可视化 广告爬虫 大数据毕业设计 深度学习 机器学习

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

vue3学习四

七 标签ref属性 设置标签ref属性&#xff0c;类似于设置标签id。 普通标签 <template name"test4"> <p ref"title" id"title" click"showinfo">VIEW4</p> <View3/><script lang"ts" setup>…

F - Building Roads S

Description Farmer John had just acquired several new farms! He wants to connect the farms with roads so that he can travel from any farm to any other farm via a sequence of roads; roads already connect some of the farms. Each of the N (1 ≤ N ≤ 1,000) …

UnityShader学习笔记——多种光源

——内容源自唐老狮的shader课程 目录 1.光源类型 2.判断光源类型 2.1.在哪判断 2.2.如何判断 3.光照衰减 3.1.基本概念 3.2.unity中的光照衰减 3.3.光源空间变换矩阵 4.点光源衰减计算 5.聚光灯衰减计算 5.1.聚光灯的cookie&#xff08;灯光遮罩&#xff09; 5.2.聚…

MySql数据库SQL编写规范注意事项

MySQL数据库SQL编写规范对于提高代码可读性、增强代码维护性、优化查询性能、减少错误发生、促进标准化和团队协作以及提升开发效率等方面都具有重要意义。因此&#xff0c;在开发过程中应严格遵守SQL编写规范&#xff0c;以确保代码的质量和效率。 以下是 MySQL 数据库 SQL 编…

golang命令大全12--命令速查表

至此&#xff0c;本系列博文已将golang的各种应用场景的命令都介绍了一遍&#xff0c;通过熟练使用这些命令&#xff0c;开发者可以更高效地开发、测试和维护Go项目&#xff0c;同时也能够更好地理解和学习Go语言的特性和最佳实践。因此&#xff0c;掌握Go命令行工具是成为一名…

第十节-Sourcetree图形化使用git

一、Sourcetree和Git介绍 1.1 Git 简介 Git 是一个分布式版本控制系统&#xff08;Version Control System, VCS&#xff09;&#xff0c;由 Linus Torvalds 于 2005 年创建&#xff0c;最初是为了管理 Linux 内核开发而设计的。Git 的主要功能是跟踪文件的变更&#xff0c;帮…

微服务 day01 注册与发现 Nacos OpenFeign

目录 1.认识微服务&#xff1a; 单体架构&#xff1a; 微服务架构&#xff1a; 2.服务注册和发现 1.注册中心&#xff1a; 2.服务注册&#xff1a; 3.服务发现&#xff1a; 发现并调用服务&#xff1a; 方法1&#xff1a; 方法2&#xff1a; 方法3:OpenFeign OpenFeig…