DEV Community

Alexis
Alexis

Posted on

Java - How to Replace Text in Word Documents

In certain cases, you may need to replace text in a Word document. For instance, you misspelled someone’s name multiple times throughout your document and need to update it to the correct one; or you need to generate Word documents from a template by replacing placeholder text. To automate this operation, this article will explain how to replace text in Word documents in Java using Free Spire.Doc for Java library. It covers the following topics:

Add Dependencies

Method 1: If you are using maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Method 2: If you are not using maven, you can download the JAR file from this link, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.

Replace Text in Document

Free Spire.Doc for Java provides a Document class which represents a Word document. This class exposes a replace method which enables developers to replace a certain text within the document.

The following code example explains how to replace text in a Word document using Java:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class ReplaceTextInDocument {
    public static void main(String []args){
        //Load a Word document
        Document document = new Document("Input.docx");

        // Replace a specific text
        document.replace("Java", "Replace", false, true);

        //Save the result document
        document.saveToFile("ReplaceTextInDocument.docx", FileFormat.Docx);
    }
}
Enter fullscreen mode Exit fullscreen mode

Replace text in a Word document using Java

Replace Text in Table

The above example replaces all occurrences of a text within the whole document. If you only want to replace text within a specific table, you can use the replace method of Table class to implement this task.

The following code example explains how to replace text in a table in a Word document using Java:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.Table;

import java.util.HashMap;
import java.util.Map;

public class ReplaceTextInTable {
    public static void main(String []args){
        //Load a Word document
        Document document = new Document("Table.docx");
        //Get the first section
        Section section = document.getSections().get(0);
        //Get the first table in the section
        Table table = section.getTables().get(0);

        //Create a map of values
        Map<String, String> map = new HashMap();
        map.put("$name","Alex Brian");
        map.put("$age","28");
        map.put("$gender","Male");
        map.put("$phone","(555)85430000");
        map.put("$address","Brooklyn, NY 11201");
        map.put("$email","alex.brian@email.com");

        //Replace text in the table
        for (Map.Entry<String, String> entry : map.entrySet()) {
            table.replace(entry.getKey(), entry.getValue(), false, true);
        }

        //Save the result document
        document.saveToFile("ReplaceTextInTable.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Replace text in table in Word using Java

Replace Text with Image

Actually, Free Spire.Doc for Java doesn’t provide a direct method to replace text with image. You can achieve this feature by finding the index position of the text, inserting an image to the position, and then removing the text from the document.

The following code example explains how to replace text with image in a Word document using Java:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

public class ReplaceTextWithImage {
    public static void main(String []args){
        //Load a Word document
        Document document = new Document("ReplaceTextInTable.docx");

        //Search for text
        TextSelection textSelection = document.findString("$photo", false, true);
        //Load an image
        DocPicture pic = new DocPicture(document);
        pic.loadImage("photo.png");
        //Get the index position of the text
        TextRange range = textSelection.getAsOneRange();
        int index = range.getOwnerParagraph().getChildObjects().indexOf(range);
        //Insert the image to the position
        range.getOwnerParagraph().getChildObjects().insert(index,pic);
        //Remove the text
        range.getOwnerParagraph().getChildObjects().remove(range);

        //Save the result document
        document.saveToFile("ReplaceTextWithImage.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Replace text with image in Word using Java

Replace Text using Regular Expression (RegEx)

A regular expression is a pattern that the regular expression engine attempts to match in input text. It provides a powerful, flexible, and efficient method for processing text.

The following code example explains how to replace text by regular expression in Word using Java:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.util.regex.Pattern;

public class ReplaceTextByRegEx {
    public static void main(String []args){
        //Create word document
        Document doc = new Document();

        // Load the document from disk.
        doc.loadFromFile("Regex.docx");

        //Create a RegEx to replace text starting with #
        Pattern regex=Pattern.compile("\\#\\w+\\b");
        //Replace text by the regex
        doc.replace(regex,"KeyBoard");

        //Save the result document
        doc.saveToFile("ReplaceTextByRegex.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Replace text by regex in Word using Java

Conclusion

This article introduced several scenarios to replace text in a Word document. Apart from the explained scenarios, you can also use Free Spire.Doc for Java library to replace text with a Word document, replace text with HTML, replace text with table etc., but I'm ending the article here to keep it within limits. If you are interested, you can try it by yourself.

Latest comments (0)