How to Find and Replace Text in a Word Document in Java

How to Find and Replace Text in a Word Document in Java

Aspose.Words FOSS for Java replaces text in a Word document with the replace method of a Range. This guide fills a placeholder in a template document and saves the result as a new file, with the library from Maven Central.

Step-by-Step Guide

Step 1: Install the Package

Add the package to your build. The library needs Java 8 or later.

<dependency>
  <groupId>org.aspose</groupId>
  <artifactId>aspose-words-foss</artifactId>
  <version>26.3.0</version>
</dependency>

Step 2: Import the Classes

All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.


Step 3: Replace the Placeholder

Open the template with the Document constructor. getRange, inherited from Node, returns a Range object that represents the portion of a document that is contained in the node. replace replaces all occurrences of a character string pattern with a replacement string and returns the number of replacements as an int.

import com.aspose.words.*;

Document doc = new Document("contract.docx");
doc.getRange().replace("{{CLIENT_NAME}}", "Acme Corp");
doc.save("contract-filled.docx");

Common Issues and Fixes

The compiler reports cannot find symbol for Document. The com.aspose.words package is not imported. Add import com.aspose.words.*;.

Opening the template throws a FileNotFoundException. The message reads “Can’t find file” followed by the name. Check that contract.docx exists in the directory the program runs in.

The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.

Frequently Asked Questions

What does replace return?

The number of replacements: 2 when the placeholder appears twice.

Does it replace every occurrence?

Yes. It replaces all occurrences of the string, and the comparison is case-insensitive.

Can I pass options?

Yes. replace has an overload that takes FindReplaceOptions, which specifies options for find/replace operations.

See Also