DEV Community

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

Posted on • Originally published at syncfusion.com on

7 Useful Ways to Find and Replace Text in a Word Document Using C#

Finding and replacing text in a Word document is an operation that saves a lot of manual work in modifying a document. In this article, we are going to learn how to find and replace text in Word documents programmatically in C# using Syncfusion’s .NET Word Library (Essential DocIO). This does not require Microsoft Word or Office interop dependencies.

Syncfusion’s Word Library provides comprehensive APIs to find and replace text in a Word document with any desired text, image, hyperlink, paragraph, table, part of a document, or entire document. It provides options to find text by matching case and whole words. You can find each occurrence one by one or all the occurrences of a text at once in a document.

This feature saves you effort and time by helping you automatically find and replace a pattern of text in a Word document using Regex.

You can save the resultant document as a Word document (DOCX, WordML, DOC), PDF, image, HTML, RTF, and more.

The seven ways to find and replace text in a Word document using C# are:

Find and replace text in a Word document with other text using C

You can find text in a Word document and replace it with other text programmatically in C# using the Syncfusion Word Library. Unlike the Find method, the Replace method replaces all occurrences of the text. You can customize it to replace only the first occurrence of a text by setting the ReplaceFirst property of the WordDocument class to true.

The following code example illustrates how to replace all occurrences of a misspelled word with the correctly spelled word.

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all occurrences of a misspelled word and replaces with properly spelled word.
    document.Replace("Cyles", "Cycles", true, true);
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find a misspelled word and replace it with properly spelled word
Find a misspelled word and replace it with properly spelled word

The complete working example can be downloaded from this GitHub location.

Find and replace text in Word document with an image using C

You can find placeholder text in a Word document and replace it with any desired image programmatically in C# using the Syncfusion Word Library.

The following code example illustrates how to do this.

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all the image placeholder text in the Word document.
    TextSelection[] textSelections = document.FindAll(new Regex("^//(.*)"));
    for (int i = 0; i < textSelections.Length; i++)
    {
        //Replaces the image placeholder text with desired image.
        Stream imageStream = File.OpenRead(Path.GetFullPath(@"../../../" + textSelections[i].SelectedText + ".png"));
        WParagraph paragraph = new WParagraph(document);
        WPicture picture = paragraph.AppendPicture(imageStream) as WPicture;
        imageStream.Dispose();
        TextSelection newSelection = new TextSelection(paragraph, 0, 1);
        TextBodyPart bodyPart = new TextBodyPart(document);
        bodyPart.BodyItems.Add(paragraph);
        document.Replace(textSelections[i].SelectedText, bodyPart, true, true);
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find text and replace it with desired image
Find text and replace it with desired image

The complete working example can be downloaded from this GitHub location.

Find and replace a pattern of text with a merge field using C

Syncfusion’s Word Library allows you to find and replace a pattern of text in a Word document with merge fields programmatically in C# using Regex.

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 desired merge fields.

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all the placeholder text enclosed within '«' and '»' in the Word document.
    TextSelection[] textSelections = document.FindAll(new Regex("«([(?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[i] = textSelections[i].SelectedText;
    }
    for (int i = 0; i < searchedPlaceholders.Length; i++)
    {
        //Replaces the placeholder text enclosed within '«' and '»' with desired merge field.
        WParagraph paragraph = new WParagraph(document);
        paragraph.AppendField(searchedPlaceholders[i].TrimStart('«').TrimEnd('»'), FieldType.FieldMergeField);
        TextSelection newSelection = new TextSelection(paragraph, 0, paragraph.Items.Count);
        TextBodyPart bodyPart = new TextBodyPart(document);
        bodyPart.BodyItems.Add(paragraph);
        document.Replace(searchedPlaceholders[i], bodyPart, true, true, true);
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find a pattern of text and replace it with merge fields
Find a pattern of text and replace it with merge fields

The complete working example can be downloaded from this GitHub location.

Find and replace text in a Word document with a table using C

You can find placeholder text in a Word document and replace it with a table programmatically in C# using the Syncfusion Word Library.

The following code example illustrates how to do this.

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Creates a new table.
    WTable table = new WTable(document);
    table.ResetCells(1, 6);
    table[0, 0].Width = 52f;
    table[0, 0].AddParagraph().AppendText("Supplier ID");
    table[0, 1].Width = 128f;
    table[0, 1].AddParagraph().AppendText("Company Name");
    table[0, 2].Width = 70f;
    table[0, 2].AddParagraph().AppendText("Contact Name");
    table[0, 3].Width = 92f;
    table[0, 3].AddParagraph().AppendText("Address");
    table[0, 4].Width = 66.5f;
    table[0, 4].AddParagraph().AppendText("City");
    table[0, 5].Width = 56f;
    table[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);
    //Replaces the table placeholder text with a new table
    TextBodyPart bodyPart = new TextBodyPart(document);
    bodyPart.BodyItems.Add(table);
    document.Replace("[Suppliers table]", bodyPart, true, true, true);
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find text and replace it with a desired table
Find text and replace it with a desired table

The complete working example can be downloaded from this GitHub location.

Find and replace text in Word document with another document using C

The Syncfusion Word Library lets you find and replace text with another Word document programmatically in C#.

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

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //Finds all the content placeholder text in the Word document.
    TextSelection[] textSelections = document.FindAll(new Regex(@"\[(.*)\]"));
    for (int i = 0; i < textSelections.Length; i++)
    {
        //Replaces the content placeholder text with desired Word document.
        docStream = File.OpenRead(Path.GetFullPath(@"../../../" + textSelections[i].SelectedText.TrimStart('[').TrimEnd(']') + ".docx"));
        WordDocument subDocument = new WordDocument(docStream, FormatType.Docx);
        docStream.Dispose();
        document.Replace(textSelections[i].SelectedText, subDocument, true, true);
        subDocument.Dispose();
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find text and replace it with another Word document
Find text and replace it with another Word document

The complete working example can be downloaded from this GitHub location.

Find and replace text extending to several paragraphs in C

Apart from finding text in a paragraph, you can also find and replace text that extends to several paragraphs in a Word document. You can find the first occurrence of the text that extends to several paragraphs by using the FindSingleLine method. Find the next occurrences of the text by using the FindNextSingleLine method. Similarly, you can replace text that extends to several paragraphs by using ReplaceSingleLine method.

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

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    docStream = File.OpenRead(Path.GetFullPath(@"../../../Source.docx"));
    WordDocument subDocument = new WordDocument(docStream, FormatType.Docx);
    docStream.Dispose();
    //Gets the content from another Word document to replace with.
    TextBodyPart replacePart = new TextBodyPart(subDocument);
    foreach (TextBodyItem bodyItem in subDocument.LastSection.Body.ChildEntities)
    {
        replacePart.BodyItems.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.Dispose();
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find text that extends to several paragraphs and replace it
Find text that extends to several paragraphs and replace it

The complete working example can be downloaded from this GitHub location.

Find text in a Word document and format it using C

Using the Syncfusion Word Library, you can find text in a Word document and format or highlight it programmatically in C#. You can find the first occurrence of text using the Find method. Find the next occurrences of the text using the FindNext method.

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

//Creates new Word document instance for word processing.
using (WordDocument document = new WordDocument())
{
    //Opens the input Word document.
    Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
    document.Open(docStream, FormatType.Docx);
    docStream.Dispose();
    //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[i].GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
    }
    //Saves the resultant file in the given path.
    docStream = File.Create(Path.GetFullPath(@"Result.docx"));
    document.Save(docStream, FormatType.Docx);
    docStream.Dispose();
}

Find text and highlight it
Find text and highlight it

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

The complete working example can be downloaded from this GitHub location.

Summary

Thank you for taking the time to read this blog. I hope it may have clarified finding and replacing text in Word documents using the Syncfusion Word Library. Take a moment to peruse the documentation, where you’ll find other options and features, all with accompanying code examples. Using the Library, you can create, edit, and merge Word documents, as well as convert them to PDF, image, HTML, RTF, and other formats.

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

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

If you have any questions about these features, please let us know in the comments below. You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

The post 7 Useful Ways to Find and Replace Text in a Word Document Using C# appeared first on Syncfusion Blogs.

Top comments (0)