DEV Community

Cover image for 7 Smart Ways to Find and Replace Text in a Word Document Using Java
Suresh Mohan for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

7 Smart Ways to Find and Replace Text in a Word Document Using Java

Our Syncfusion Java Word Library (Essential DocIO) allows you to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies. The find and replace feature in the Java Word Library allows you to find text and replace it with any desired text, image, hyperlink, paragraph, table, part of a document, or entire document. It also allows you to quickly search for text by matching case and whole words. You can find each occurrence one by one or highlight all instances at once in a document.

This feature saves your time and effort by allowing you to use the Regex class. This class will automatically locate and replace a pattern of text in a lengthy Word document.

You can save the results in Word (DOCX, WordML), HTML, and RTF formats.

In this blog, we are going to learn these seven smart ways to find and replace text using our Java Word Library:

Find and replace text in a Word document with other text

The Java Word Library allows you to find text in a Word document and replace all the occurrences of that text programmatically.

The following code example illustrates how to replace all occurrences of a misspelled word with the correctly spelled word. Use the setReplaceFirst property to replace only the first occurrence of the text.

// Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("Template.docx"));
// Finds all occurrences of a misspelled word and replaces them with the properly spelled word.
document.replace("Cyles", "Cycles", true, true);
// Saves the resultant file in the given path.
document.save("Result.docx");
document.close();
Enter fullscreen mode Exit fullscreen mode

Find a Misspelled Word and Replace it with the Properly Spelled Word
Find a Misspelled Word and Replace it with the Properly Spelled Word

Note: For more information, refer to the Find and Replace Text in a Java Word Document demo.

Find and replace text in a Word document with an image

You can easily find placeholder text in a Word document and replace it with any desired image programmatically using our Java Word Library.

The following code example illustrates how to achieve this programmatically.

//Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("FindAndReplaceImage_Template.docx"));
//Finds all the image placeholder text in the Word document.
TextSelection[] textSelections = document.findAll(Pattern.compile(MatchSupport.trimPattern("^//(.*)")));
for (int i = 0; i < textSelections.length; i++) {
   // Replaces the image placeholder text with desired image.
   WParagraph paragraph = new WParagraph(document);
   WPicture picture = (WPicture) paragraph
   .appendPicture(new FileInputStream(getDataDir(textSelections[i].getSelectedText() + ".png")));
   TextSelection newSelection = new TextSelection(paragraph, 0, 1);
   TextBodyPart bodyPart = new TextBodyPart(document);
   bodyPart.getBodyItems().add(paragraph);
   document.replace(textSelections[i].getSelectedText(), bodyPart, true, true);
}
//Saves the resultant file in the given path.
document.save("Result.docx");
document.close();
Enter fullscreen mode Exit fullscreen mode

Find Text and Replace it with a Desired Image
Find Text and Replace it with a Desired Image

Note: For more information, refer to the Replace Text with Image in a Java Word Document demo.

Find and replace a pattern of text with a merge field

The Java Word Library allows you to easily find and replace words that follow a particular pattern using the Regex class.

The following code example illustrates how to create a mail merge template by replacing a pattern of text (enclosed within « and ») in a Word document with the required merge fields.

// Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("ReplaceWithMergeFileds_Template.docx"));
// Finds all the placeholder text enclosed within '«' and '»' in the Word document.
TextSelection[] textSelections = document.findAll(
Pattern.compile(MatchSupport.trimPattern("«([(?i)image(?-i)]*:*[a-zA-Z0-9]*:*[a-zA-Z0-9]+)»")));
String[] searchedPlaceholders = new String[textSelections.length];
for (int i = 0; i < textSelections.length; i++) 
{
   searchedPlaceholders[(int) i] = textSelections[(int) i].getSelectedText();
}
for (int i = 0; i < searchedPlaceholders.length; i++) 
{
   WParagraph paragraph = new WParagraph(document);
   // Replaces the placeholder text enclosed within '«' and '»' with the desired merge field.
   paragraph.appendField(StringSupport.trimEnd(StringSupport.trimStart(searchedPlaceholders[i], '«'), '»'),
   FieldType.FieldMergeField);
   TextSelection newSelection = new TextSelection(paragraph, 0, paragraph.getItems().getCount());
   TextBodyPart bodyPart = new TextBodyPart(document);
   bodyPart.getBodyItems().add(paragraph);
   document.replace(searchedPlaceholders[(int) i], bodyPart, true, true, true);
}
// Saves the resultant file in the given path.
document.save("Result.docx");
document.close();
Enter fullscreen mode Exit fullscreen mode

Find a Pattern of Text and Replace it with Merge Fields
Find a Pattern of Text and Replace it with Merge Fields

Note: For more information, refer to the Replace Text with Merge Field in a Java Word Document demo.

Find and replace text in a Word document with a table

Also, you can find placeholder text in a Word document and replace it with a table using our Java Word Library.

Refer to the following code example.

// Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("ReplaceTextWithTable.docx");
// Creates a new table.
WTable table = new WTable(document);
table.resetCells(1, 6);
table.get(0, 0).setWidth(52f);
table.get(0, 0).addParagraph().appendText("Supplier ID");
table.get(0, 1).setWidth(128f);
table.get(0, 1).addParagraph().appendText("Company Name");
table.get(0, 2).setWidth(70f);
table.get(0, 2).addParagraph().appendText("Contact Name");
table.get(0, 3).setWidth(92f);
table.get(0, 3).addParagraph().appendText("Address");
table.get(0, 4).setWidth(66.5f);
table.get(0, 4).addParagraph().appendText("City");
table.get(0, 5).setWidth(56f);
table.get(0, 5).addParagraph().appendText("Country");
// Imports data to the table.
importDataToTable(table);
// Applies the built-in table style (Medium Shading 1 Accent 1) to the table.
table.applyStyle(BuiltinTableStyle.MediumShading1Accent1);
TextBodyPart bodyPart = new TextBodyPart(document);
bodyPart.getBodyItems().add(table);
// Replaces the table placeholder text with a new table.
document.replace("[Suppliers table]", bodyPart, true, true, true);
// Saves the resultant file in the given path.
document.save("Result.docx");
Enter fullscreen mode Exit fullscreen mode

Find Text and Replace it with a Desired Table
Find Text and Replace it with a Desired Table

Note: For more information, refer to the Replace Text with Table in a Java Word Document demo.

Find and replace text in a Word document with another document

The Java Word Library also provides support to find and replace text with another word document programmatically.

The following code example illustrates how to merge or combine Word documents by replacing text with another document (the content of a subheading).

//Opens the Word template document.
WordDocument document = new WordDocument(getDataDir("ReplaceTextWithDocument_Template.docx"),FormatType.Docx);
TextSelection[] textSelections = document.findAll(Pattern.compile(MatchSupport.trimPattern("\\[(.*)\\]")));
for(int i = 0;i< textSelections.length;i++)
{
   WordDocument subDocument = new WordDocument(getDataDir( StringSupport.trimEnd(StringSupport.trimStart(textSelections[i].getSelectedText(), '['), ']')+ ".docx"),FormatType.Docx);
   document.replace(textSelections[(int)i].getSelectedText(),subDocument,true,true);
   subDocument.close();
}
//Saves the Word document.
document.save("Result.docx");
//Closes the document.
document.close();
Enter fullscreen mode Exit fullscreen mode

Find Text and Replace it with Another Word Document
Find Text and Replace it with Another Word Document

Note: For more information, refer to the Replace Text with Another Document Using Java Word Library demo.

Find and replace text extending to several paragraphs

The Java Word Library offers some more APIs to find and replace text that extends to several paragraphs in a Word document. The following methods will assist you in various cases:

  • findSingleLine – Finds the first occurrence of the text that extends to several paragraphs in a document.
  • findNextSingleLine – Finds the next occurrence of the text that extends to several paragraphs in a document.
  • replaceSingleLine – Replaces all occurrences of text that extend to several paragraphs in a document.

The following code example illustrates how to replace text that extends to several paragraphs.

//Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("FindAndReplaceSeveralParagraphs_Template.docx"),FormatType.Docx);
WordDocument subDocument = new WordDocument(getDataDir("Source.docx"), FormatType.Docx);//Gets the content from another Word document to replace.
TextBodyPart replacePart = new TextBodyPart(subDocument);
for(Object bodyItem_tempObj : subDocument.getLastSection().getBody().getChildEntities())
{
   TextBodyItem bodyItem = (TextBodyItem)bodyItem_tempObj;
   replacePart.getBodyItems().add(bodyItem.clone());
}
String placeholderText = "Suppliers/Vendors of Northwind"+"Customers of Northwind"+"Employee details of Northwind traders"+"The product information"+"The inventory details"+"The shippers"+"Purchase Order transactions"+"Sales Order transaction"+"Inventory transactions"+"Invoices"+"[end replace]";
//Finds the text that extends to several paragraphs and replaces it with desired content.
document.replaceSingleLine(placeholderText,replacePart,false,false);
subDocument.close();
//Saves the Word document.
document.save("Result.docx");
//Closes the document.
document.close();
Enter fullscreen mode Exit fullscreen mode

Find Text that Extends to Several Paragraphs and Replace It
Find Text that Extends to Several Paragraphs and Replace It

Note: For more information, refer to the Find and Replace Text Extending to Several Paragraphs in a Java Word Document example.

Find and format text in a Word document

With the Syncfusion Java Word Library, you can easily find text in a Word document and format or highlight it programmatically. Find the first occurrence of the text using the find method. Find the next occurrence of the text using the findNext method.

The following code example illustrates how to find all occurrences of a text and highlight them.

//Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("FindAndHighlightText_Template.docx"), FormatType.Docx);
//Finds all occurrence of the text in the Word document.
TextSelection[] textSelections = document.findAll("Adventure",true,true);
for(int i = 0;i<textSelections.length;i++)
{
  //Sets the highlight color for the searched text as Yellow.
  textSelections[(int)i].getAsOneRange().getCharacterFormat().setHighlightColor(ColorSupport.getYellow());
}
//Saves the Word document.
document.save("Result.docx");
//Closes the document.
document.close();
Enter fullscreen mode Exit fullscreen mode

Find and Highlight Text in Java Word Library
Find and Highlight Text in Java Word Library

Similarly, you can automate the process of highlighting or underlining any misspelled words in a Word document without using Microsoft Word.

Note: For more information, refer to the Find and Highlight Text in a Java Word Document demo.

Summary

Thanks for reading! In this blog, we have seen seven smart ways to find and replace text in a Word document using the Syncfusion Java Word Library (Essential DocIO). Take a moment to peruse the documentation, where you’ll find other options and features, all with accompanying code examples. Using the Word Library, you can create, edit, and merge Word documents, as well as convert them to HTML, RTF, and other formats. Try out the methods discussed in this blog post and leave your feedback in the comments section below!

If you are new to our Word Library, it is highly recommended that you follow our Getting Started guide.

Are you already a Syncfusion user? You can download the product setup. If you’re not yet a Syncfusion user, you can download a 30-day free trial.

You can also contact us through our support forums, Direct-Trac, or feedback portal. We are happy to assist you!

Related blogs

Top comments (0)