C#/VB.NET: Find and Highlight Text in Word

2022-08-09 06:38:00 Written by  support iceblue
Rate this item
(0 votes)

Finding specific text or phrases in a long Word document can be a bit of a hassle. Fortunately, MS Word provides the "Find" function to locate specific content in a document quickly. You can also highlight the found content with a background color to ensure that they won't be overlooked by the readers. This article will demonstrate how to programmatically find and highlight text in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Find and Highlight Text in a Word Document

The detailed steps are as follows.

  • Create a Document instance
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find all matching text in the document using Document.FindAllString(string matchString, bool caseSensitive, bool wholeWord) method.
  • Loop through all matching text in the document.
  • Get the text range of a specific matching text using TextSelection.GetAsOneRange() method, and then set its highlight color using TextRange.CharacterFormat.HighlightColor property.
  • Save the result file using Document.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace FindHighlight
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a sample Word document 
            document.LoadFromFile("input.docx");

            //Find all matching text in the document
            TextSelection[] text = document.FindAllString("transcendentalism", false, true);

            //Loop through all matching text and set highlight color for them
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            //Save the result file
            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Find and Highlight Text in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 01 June 2023 01:17