当前位置: 代码网 > it编程>编程语言>Java > Java实现读取Word模板文档并替换内容生成新文档

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

2025年02月10日 Java 我要评论
在实际开发中,经常会遇到需要根据 word 模板生成特定文档的需求,比如合同、报告等。咱们可以使用 apache poi 库来读取 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 代码实现

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 模板文件

fileinputstream fis = new fileinputstream("template.docx");
xwpfdocument document = new xwpfdocument(fis);

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

准备要替换的数据

map<string, string> data = new hashmap<>();
data.put("{name}", "张三");
simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
data.put("{date}", sdf.format(new date()));

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

替换文档中的占位符

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 文档

fileoutputstream fos = new fileoutputstream("output.docx");
document.write(fos);
fos.close();
fis.close();

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

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

到此这篇关于java实现读取word模板文档并替换内容生成新文档的文章就介绍到这了,更多相关java读取word模板并替换内容内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com