How to find and replace Text on Word document programmatically
Microsoft Word's Find feature is very important while we deal with a Word document with a large amount of contents. With the help of a third party word API to use the find and replace feature on word documents in C#.
Microsoft Word's Find feature is very important while we deal with a Word document with a large amount of contents. It enables us to search through the whole word documents for a particular text, phrase and sentences. We can choose to replace the searched text automatically and we can choose to replace some of them from the searched results. But if we need to use the find and replace feature programmatically, we may find it is complex and not easy to do it. This article will show you how to use the find and replace feature on word documents in C# with the help of a 100% free .NET API Spire.Doc.
In Microsoft word we can find special text and then replace them with the other words as below easily.
Now I will show the simple solution of how to find and replace the text string in C# by using Free Spire.Doc.
Introduction of Free Spire.Doc:
Free Spire.Doc is a free and standalone word API which enables developers to generate, read, write, save, print and convert documents on any .NET applications.
Then get the Spire.Doc.dll on .NET platform from Nuget. It is simple and clean. You can easily add reference Spire.doc.dll to your applications.
Step 1: Create a new instance of Spire.Doc.document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("sample.docx");
Step 2: Use the new text to replace the desired word string directly by using the Document.Replace method.
doc.Replace("New Zealand", "NZ", false, true);
Step 3: Save the document to file.
doc.SaveToFile("Replace.docx", FileFormat.Docx);
After saving the word document, the word "New Zealand" will be replaced by NZ and there is no any highlight color on it.
Sometimes, we need to highlight the changed wording to make the changes more visible and Free Spire.Doc can also supports to highlight the wording when replace it. Here comes to the method of replace the wording and highlight it.
Find the text "New Zealand" from the whole word document and set the highlight color and the new text for the searched word string.
TextSelection[] text = doc.FindAllString("New Zealand", false, true);
foreach (TextSelection seletion in text)
{
seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
seletion.GetAsOneRange().Text = "NZ";
}
Effective screenshot:
Conclusion: It is quite easy for us to use free Spire.Doc to find and replace the text on the word document in C#. Free Spire.Doc is a powerful and free C# word library without Word automation and any other third party add-ins. It is worthy your try on it.