[Java] Find and Replace Text in Word Documents
When manipulating a Word document, sometimes we may encounter a situation where we need to replace the specified text with new text. In this articel, I will introduce 2 ways to find and replace text by using Free Spire.Doc for Java .
1. Find and replace all matched text with new text.
2. Find and replace the first matched text with new text.
Installation
Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
The original document is shown as below:
【Example 1】Replaces all of the “Nathanial Hawthorne” text with “Herman Melville” by using the replace method.
import com.spire.doc.*;
public class ReplaceText {
public static void main(String[] args){
//Load the Word document
Document document = new Document("Herman.docx");
//Replace the specified text with new text
document.replace("Nathanial Hawthorne", "Herman Melville", false, true);
//Save the document
document.saveToFile("ReplaceAllMatchedText.docx", FileFormat.Docx_2013);
}
}
Output:
【Example 2】Replaces the first “Nathanial Hawthorne” text with “Herman Melville” by using the setReplaceFirst method.
import com.spire.doc.*;
public class ReplaceText {
public static void main(String[] args){
//Load the Word document
Document document = new Document("Herman.docx");
//Replace the first matched text
document.setReplaceFirst(true);
//Replace with new text
document.replace("Nathanial Hawthorne", "Herman Melville", false, true);
//Save the document
document.saveToFile("ReplaceFirstMatchedText.docx", FileFormat.Docx_2013);
}
}
Output: