Find and Replace text in a Word file with C# and VB.NET

GemBox.Document offers several ways in which you can manipulate a Word document's content to import new or replace existing data using C# or VB.NET code. For instance, you can use Mail Merge, Update Form, Content Controls Mapping, Modify Bookmarks, or the following find and replace approach.

You can easily find all the parts of a Word document that contain the specified text or match the specified regular expression and replace them with desired text by using one of the ContentRange.Replace methods.

You can also search for all occurrences of a specified String or Regex using one of the ContentRange.Find methods and process the resulting ContentRange objects as needed. This approach is useful when you need a more complex replacement, like replacing your placeholders with hyperlinks, tables, pictures, or some other content.

The following example shows how you can search for all occurrences of some placeholder text in a document and highlight or replace them with any desired text and optional formatting.

Finding and replacing or highlighting text from Word document in C# and VB.NET
Screenshot of a Word document with found and replaced text
Upload your file (Drag file here)
using System;
using System.Linq;
using GemBox.Document;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = DocumentModel.Load("%InputFileName%");

        // The easiest way how you can find and replace text is with "Replace" method.
        document.Content.Replace("%FirstName%", "John");
        document.Content.Replace("%LastName%", "Doe");
        document.Content.Replace("%Date%", DateTime.Today.ToLongDateString());

        // You can also find and highlight text by specifying "HighlightColor" of replacement text.
        document.Content.Replace("membership", "membership", new CharacterFormat() { HighlightColor = Color.Yellow });

        // You can also search for placeholder text with "Find" method and then achieve more complex replacement.
        // The "Reverse" extension method is used when iterating through document's content
        // to avoid any possible invalid state when replacing the content within iteration.

        // Replace text with text that has different formatting.
        foreach (ContentRange searchedContent in document.Content.Find("%Price%").Reverse())
        {
            ContentRange replacedContent = searchedContent.LoadText("$",
                new CharacterFormat() { Size = 14, FontColor = Color.Purple });
            replacedContent.End.LoadText("100.00",
                new CharacterFormat() { Size = 11, FontColor = Color.Purple });
        }

        // Replace text with hyperlink.
        foreach (ContentRange searchedContent in document.Content.Find("%Email%").Reverse())
        {
            Hyperlink emailLink = new Hyperlink(document, "mailto:john.doe@example.com", "John.Doe@example.com");
            searchedContent.Set(emailLink.Content);
        }

        document.Save("FoundAndReplacedText.%OutputFileType%");
    }
}
Imports System
Imports System.Linq
Imports GemBox.Document

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document = DocumentModel.Load("%InputFileName%")

        ' The easiest way how you can find and replace text is with "Replace" method.
        document.Content.Replace("%FirstName%", "John")
        document.Content.Replace("%LastName%", "Doe")
        document.Content.Replace("%Date%", DateTime.Today.ToLongDateString())

        ' You can also find and highlight text by specifying "HighlightColor" of replacement text.
        document.Content.Replace("membership", "membership", New CharacterFormat() With {.HighlightColor = Color.Yellow})

        ' You can also search for placeholder text with "Find" method and then achieve more complex replacement.
        ' The "Reverse" extension method is used when iterating through document's content
        ' to avoid any possible invalid state when replacing the content within iteration.

        ' Replace text with text that has different formatting.
        For Each searchedContent As ContentRange In document.Content.Find("%Price%").Reverse()

            Dim replacedContent As ContentRange = searchedContent.LoadText("$",
                New CharacterFormat() With {.Size = 14, .FontColor = Color.Purple})
            replacedContent.End.LoadText("100.00",
                New CharacterFormat() With {.Size = 11, .FontColor = Color.Purple})

        Next

        ' Replace text with hyperlink.
        For Each searchedContent As ContentRange In document.Content.Find("%Email%").Reverse()

            Dim emailLink As New Hyperlink(document, "mailto:john.doe@example.com", "John.Doe@example.com")
            searchedContent.Set(emailLink.Content)

        Next

        document.Save("FoundAndReplacedText.%OutputFileType%")

    End Sub
End Module

Instead of just replacing the document's text with another plain text, the following example shows how you can replace placeholder text in a Word document with Picture and Table elements.

Also, the following example shows how you can specify your replacement text in HTML format.

Finding and replacing text from Word document with image and table in C# and VB.NET
Screenshot of a Word file with text replaced with an image and a table
Upload your file (Drag file here)
using System.Linq;
using GemBox.Document;
using GemBox.Document.Tables;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = DocumentModel.Load("%InputFileName%");

        var dummyText = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa.";

        // Find an image placeholder.
        var picturePlaceholder = document.Content.Find("%Portrait%").First();
        var picture = new Picture(document, "%#avatar.png%");

        // Replace the placeholder text with image.
        picturePlaceholder.Set(picture.Content);

        // Find an HTML placeholder.
        var htmlPlaceholder = document.Content.Find("%AboutMe%").First();
        var html =
$@"<ul style='font:11pt Calibri;'>
    <li style='color:red;'>{dummyText}</li>
    <li style='color:green;'>{dummyText}</li>
    <li style='color:blue;'>{dummyText}</li>
</ul>";

        // Replace the placeholder text with HTML formatted text.
        htmlPlaceholder.LoadText(html, new HtmlLoadOptions());

        // Find a table placeholder.
        var tablePlaceholder = document.Content.Find("%JobHistory%").First();

        var table = new Table(document,
            new TableRow(document,
                new TableCell(document, new Paragraph(document, "2021 - 2030")),
                new TableCell(document, new Paragraph(document, dummyText))),
            new TableRow(document,
                new TableCell(document, new Paragraph(document, "2011 - 2020")),
                new TableCell(document, new Paragraph(document, dummyText))),
            new TableRow(document,
                new TableCell(document, new Paragraph(document, "2001 - 2010")),
                new TableCell(document, new Paragraph(document, dummyText))));

        table.Columns.Add(new TableColumn(70));
        table.Columns.Add(new TableColumn(250));
        table.TableFormat.AutomaticallyResizeToFitContents = false;

        // Delete the placeholder text and insert the table before it.
        tablePlaceholder = tablePlaceholder.LoadText(string.Empty);
        tablePlaceholder.Start.InsertRange(table.Content);

        document.Save("FoundAndReplacedContent.%OutputFileType%");
    }
}
Imports System.Linq
Imports GemBox.Document
Imports GemBox.Document.Tables

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document = DocumentModel.Load("%InputFileName%")

        Dim dummyText = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa."

        ' Find an image placeholder.
        Dim picturePlaceholder = document.Content.Find("%Portrait%").First()
        Dim picture As New Picture(document, "%#avatar.png%")

        ' Replace the placeholder text with image.
        picturePlaceholder.Set(picture.Content)

        ' Find an HTML placeholder.
        Dim htmlPlaceholder = document.Content.Find("%AboutMe%").First()
        Dim html =
$"<ul style='font:11pt Calibri;'>
    <li style='color:red;'>{dummyText}</li>
    <li style='color:green;'>{dummyText}</li>
    <li style='color:blue;'>{dummyText}</li>
</ul>"

        ' Replace the placeholder text with HTML formatted text.
        htmlPlaceholder.LoadText(html, New HtmlLoadOptions())

        ' Find a table placeholder.
        Dim tablePlaceholder = document.Content.Find("%JobHistory%").First()

        Dim table As New Table(document,
            New TableRow(document,
                New TableCell(document, New Paragraph(document, "2021 - 2030")),
                New TableCell(document, New Paragraph(document, dummyText))),
            New TableRow(document,
                New TableCell(document, New Paragraph(document, "2011 - 2020")),
                New TableCell(document, New Paragraph(document, dummyText))),
            New TableRow(document,
                New TableCell(document, New Paragraph(document, "2001 - 2010")),
                New TableCell(document, New Paragraph(document, dummyText))))

        table.Columns.Add(New TableColumn(70))
        table.Columns.Add(New TableColumn(250))
        table.TableFormat.AutomaticallyResizeToFitContents = False

        ' Delete the placeholder text and insert the table before it.
        tablePlaceholder = tablePlaceholder.LoadText(String.Empty)
        tablePlaceholder.Start.InsertRange(table.Content)

        document.Save("FoundAndReplacedContent.%OutputFileType%")

    End Sub
End Module

Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.


Like it?

Download Buy

If you want to try the GemBox.Document yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.