SoFunction
Updated on 2025-04-06

Java implementation reads Word template documents and replaces content to generate new documents

In actual development, you often encounter the need to generate specific documents based on Word templates, such as contracts, reports, etc. We can use the Apache POI library to read Word template documents, then replace the specified contents, and finally generate a new document. Next, I will tell you in detail how to do it.

1. Introduce dependencies

If you are using a Maven project, add the following dependencies in :

<dependencies>
    <!-- Apache POI deal with Word document -->
    <dependency>
        <groupId></groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
</dependencies>

2. Create a Word template

First, create a Word template file, using specific placeholders in the template to represent what needs to be replaced, such as {name}, {date}, etc. Assume that the template content is as follows:

This is a test document.
Name: {name}
Date: {date}

3. Java code implementation

import .*;
 
import .*;
import ;
import ;
import ;
import ;
 
public class WordTemplateProcessor {
    public static void main(String[] args) {
        try {
            // Read Word template files            FileInputStream fis = new FileInputStream("");
            XWPFDocument document = new XWPFDocument(fis);
 
            // Prepare the data to be replaced            Map<String, String> data = new HashMap<>();
            ("{name}", "Zhang San");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            ("{date}", (new Date()));
 
            // Replace the placeholder in the document            replacePlaceholders(document, data);
 
            // Save as a new Word document            FileOutputStream fos = new FileOutputStream("");
            (fos);
            ();
            ();
 
            ("The new Word document was generated successfully!");
        } catch (IOException e) {
            ();
            ("Creating a new Word document failed:" + ());
        }
    }
 
    private static void replacePlaceholders(XWPFDocument document, Map<String, String> data) {
        // traverse each paragraph in the document        for (XWPFParagraph paragraph : ()) {
            // Iterate through each text run object in the paragraph            for (XWPFRun run : ()) {
                String text = (0);
                if (text != null) {
                    // traverse the data map and replace the placeholder                    for (<String, String> entry : ()) {
                        String placeholder = ();
                        String replacement = ();
                        if ((placeholder)) {
                            text = (placeholder, replacement);
                            (text, 0);
                        }
                    }
                }
            }
        }
    }
}

4. Code explanation

Read Word template files

FileInputStream fis = new FileInputStream("");
XWPFDocument document = new XWPFDocument(fis);

Read the file through FileInputStream and load it into memory using the XWPFDocument class.

Prepare the data to be replaced

Map<String, String> data = new HashMap<>();
("{name}", "Zhang San");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
("{date}", (new Date()));

Create a Map object that maps the placeholder to the content to be replaced.

Replace placeholders in a document

private static void replacePlaceholders(XWPFDocument document, Map<String, String> data) {
    for (XWPFParagraph paragraph : ()) {
        for (XWPFRun run : ()) {
            String text = (0);
            if (text != null) {
                for (<String, String> entry : ()) {
                    String placeholder = ();
                    String replacement = ();
                    if ((placeholder)) {
                        text = (placeholder, replacement);
                        (text, 0);
                    }
                }
            }
        }
    }
}

Iterate through each paragraph and text run object in the document, check whether the text contains placeholders, and replace if it contains.

Save as a new Word document

FileOutputStream fos = new FileOutputStream("");
(fos);
();
();

Use FileOutputStream to save the replaced document as a file.

Follow the above steps and you can use Java to read the Word template document and replace the specified content to generate a new document. Hurry up and try it!

This is the article about Java's implementation of reading Word template documents and replacing content to generate new documents. For more related Java reading Word templates and replacing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!