C#: Find and Replace Text in Word Documents

2024-04-11 02:32:00 Written by  Administrator
Rate this item
(0 votes)

When it comes to editing documents, making changes to the text is a common task. Microsoft Word provides a robust feature called "Find and Replace" that streamlines the text editing process. With this feature, you can effortlessly locate specific words, phrases, or characters within your document and replace them in one simple action. This eliminates the need for repetitive manual searching and time-consuming edits, saving you valuable time and effort, especially when you need to make widespread changes in lengthy documents. In this article, we will explain how to find and replace text in Word documents in C# 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Find Text and Replace All Its Instances with New Text

Spire.Doc for .NET provides the Document.Replace() method that enables you to find and replace specific text in a Word document. With this method, you can seamlessly replace all instances of the target text with new content. Additionally, you have the flexibility to specify whether the search should be case-sensitive and whether whole-word matching should be considered. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Replace all instances of specific text with new text using Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ReplaceAllText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Replace all instances of specific text with new text
            document.Replace("Spire.Doc", "Eiceblue", false, true);

            //Save the result document
            document.SaveToFile("ReplaceAllText.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

C#: Find and Replace Text in Word Documents

Find Text and Replace Its First Instance with New Text

To replace the first instance of a specific text in a Word document using Spire.Doc for .NET, you can utilize the Document.ReplaceFirst property. By setting this property to true before calling the Document.Replace() method, you can change the text replacement mode to exclusively replace the first instance. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Change the text replacement mode to replace the first instance only by setting the Document.ReplaceFirst property to true.
  • Call the Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method to replace text.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ReplaceFirstText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Change the text replacement mode to replace the first instance only
            document.ReplaceFirst = true;

            //Replace the first instance of specific text with new text
            document.Replace("Spire.Doc", "Eiceblue", false, true);

            //Save the result document
            document.SaveToFile("ReplaceFirstText.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Find and Replace Text with Image

Sometimes, you may need to replace text with images for visual representation or design purposes. In Spire.Doc for .NET, replacing text with image can be achieved by inserting the image at the position of the target text and then removing the text from the document. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find specific text in the document using Document.FindAllString() method.
  • Loop through the matched text.
  • For each matched text, get the paragraph where it is located and get the position of the text in the paragraph.
  • Instantiate an object of the DocPicture class, and then load an image using DocPicture.LoadImage() method.
  • Insert the image into the paragraph at the position of the text and then remove the text from the paragraph.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ReplaceTextWithImage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Find specific text in the document
            TextSelection[] selections = document.FindAllString("Spire.Doc", true, true);

            int index = 0;
            Paragraph ownerParagraph = null;

            //Loop through the matched text
            foreach (TextSelection selection in selections)
            {
                //Get the paragraph where the text is located
                ownerParagraph = selection.GetAsOneRange().OwnerParagraph;

                //Get the index position of the text in the paragraph
                index = ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange());

                //Load an image
                DocPicture pic = new DocPicture(document);
                pic.LoadImage("img.png");

                //Insert the image into the paragraph at the index position of the text
                ownerParagraph.ChildObjects.Insert(index, pic);

                //Remove the text from the paragraph
                ownerParagraph.ChildObjects.Remove(selection.GetAsOneRange());
            }

            //Save the result document
            document.SaveToFile("ReplaceTextWithImage.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

C#: Find and Replace Text in Word Documents

Find and Replace Text using Regular Expression

Regular expressions offer a robust toolset for performing complex search and replace operations within documents. The Document.Replace() method can leverage regular expressions to search for specific text, allowing you to perform advanced search and replace operations based on specific criteria. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Instantiate an object of the Regex class to match text based on specific criteria.
  • Replace the matched text with new text using Document.Replace(Regex pattern, string replace) method.
  • Save the resulting document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using System.Text.RegularExpressions;

namespace ReplaceTextWithRegex
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Create a regex to match the text that starts with #
            Regex regex = new Regex(@"\#\w+\b");

            //Replace the matched text with new text
            document.Replace(regex, "Spire.Doc");

            //Save the result document
            document.SaveToFile("ReplaceTextWithRegex.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Find and Replace Text with Content from Another Word Document

In addition to replacing text with new text or image, Spire.Doc for .NET also enables you to replace text with content from another Word document. This can be beneficial when you are working on a predefined Word template and need to incorporate contents from other Word documents into it. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Load another Word document into an IDocument object.
  • Replace specific text in the sample document with content from another document using Document.Replace(string matchString, IDocument matchDoc, bool caseSensitive, bool wholeWord) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Interface;

namespace ReplaceTextWithDocument
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Template.docx");

            //Load another Word document
            IDocument document1 = new Document("Report.docx");

            //Replace specific text in the sample document with content from another document
            document.Replace("Annual Sales", document1, false, true);

            //Save the result document
            document.SaveToFile("ReplaceTextWithDocument.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

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, 11 April 2024 01:13