Simple Way Find And Replace Text In Word document Using C#


Recently, I've been working on a project where I needed to implement the functionality of finding and replacing text in a Word document using C#. 

Our project requires that our software can offer multiple standard templates in Word format. Users should be able to download these templates, modify them, and reuse them for printing. When users click on the print button, the software needs to fill in the data into the template, and then the customer can download it.

To achieve this, I decided to use Open XML for finding and replacing text in the Word document. While Interop is also an option for this purpose, I found Open XML more convenient for my task.

I'm going to discuss how to edit Word documents using OpenXML in C#. Let's get started.We have created a Windows form for the project. On clicking the button, we will replace the text.

Find and replace text in Word document using

I have taken the word template as you can see in the below image. In which we have customer detail, now I want to replace customer information on click on the button.

Wordtemplate

I want to replace marked text in the word document.
Step 1: Install open XML Nuget package

Install-Package DocumentFormat.OpenXml -Version 2.15.0

Find and replace text in word document openxml

Step 2: Add class in your project and copy paste the below code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace WordDocument
{

public class WordDocumentService
    {
private class WordMatchedPhrase
        {
public int charStartInFirstPar { get; set; }
public int charEndInLastPar { get; set; }

public int firstCharParOccurance { get; set; }
public int lastCharParOccurance { get; set; }
        }

public WordprocessingDocument ReplaceStringInWordDocumennt(WordprocessingDocument wordprocessingDocument, string replaceWhat, string replaceFor)
        {
            List<WordMatchedPhrase> matchedPhrases = FindWordMatchedPhrases(wordprocessingDocument, replaceWhat);

            Document document = wordprocessingDocument.MainDocumentPart.Document;
int i = 0;
bool isInPhrase = false;
bool isInEndOfPhrase = false;
foreach (Text text in document.Descendants<Text>()) // <<< Here
            {
char[] textChars = text.Text.ToCharArray();
                List<WordMatchedPhrase> curParPhrases = matchedPhrases.FindAll(a => (a.firstCharParOccurance.Equals(i) || a.lastCharParOccurance.Equals(i)));
                StringBuilder outStringBuilder = new StringBuilder();

for (int c = 0; c < textChars.Length; c++)
                {
if (isInEndOfPhrase)
                    {
                        isInPhrase = false;
                        isInEndOfPhrase = false;
                    }

foreach (var parPhrase in curParPhrases)
                    {
if (c == parPhrase.charStartInFirstPar && i == parPhrase.firstCharParOccurance)
                        {
                            outStringBuilder.Append(replaceFor);
                            isInPhrase = true;
                        }
if (c == parPhrase.charEndInLastPar && i == parPhrase.lastCharParOccurance)
                        {
                            isInEndOfPhrase = true;
                        }

                    }
if (isInPhrase == false && isInEndOfPhrase == false)
                    {
                        outStringBuilder.Append(textChars[c]);
                    }
                }
                text.Text = outStringBuilder.ToString();
                i = i + 1;
            }

return wordprocessingDocument;
        }

private List<WordMatchedPhrase> FindWordMatchedPhrases(WordprocessingDocument wordprocessingDocument, string replaceWhat)
        {
char[] replaceWhatChars = replaceWhat.ToCharArray();
int overlapsRequired = replaceWhatChars.Length;
int currentChar = 0;
int firstCharParOccurance = 0;
int lastCharParOccurance = 0;
int startChar = 0;
int endChar = 0;
            List<WordMatchedPhrase> wordMatchedPhrases = new List<WordMatchedPhrase>();
            Document document = wordprocessingDocument.MainDocumentPart.Document;
int i = 0;
foreach (Text text in document.Descendants<Text>())
            {
char[] textChars = text.Text.ToCharArray();
for (int c = 0; c < textChars.Length; c++)
                {
char compareToChar = replaceWhatChars[currentChar];
if (textChars[c] == compareToChar)
                    {
                        currentChar = currentChar + 1;
if (currentChar == 1)
                        {
                            startChar = c;
                            firstCharParOccurance = i;
                        }
if (currentChar == overlapsRequired)
                        {
                            endChar = c;
                            lastCharParOccurance = i;
                            WordMatchedPhrase matchedPhrase = new WordMatchedPhrase
                            {
                                firstCharParOccurance = firstCharParOccurance,
                                lastCharParOccurance = lastCharParOccurance,
                                charEndInLastPar = endChar,
                                charStartInFirstPar = startChar
                            };
                            wordMatchedPhrases.Add(matchedPhrase);
                            currentChar = 0;
                        }
                    }
else
                    {
                        currentChar = 0;

                    }
                }
                i = i + 1;
            }

return wordMatchedPhrases;

        }

    }
}


This C# code is responsible for finding and replacing text in a Word document using Open XML. 

  • WordMatchedPhrase Class: nested class within WordDocumentService. It represents a matched phrase within the Word document, storing information about the start and end positions of the phrase within the paragraphs.
  • ReplaceStringInWordDocument Method: replaces occurrences of a specified string (replaceWhat) with another string (replaceFor) in the Word document. It takes a WordprocessingDocument object representing the Word document as input. It iterates through the document's paragraphs and text elements to find and replace the target string. It uses the FindWordMatchedPhrases method to locate occurrences of the target string.
  • FindWordMatchedPhrases Method: finds all occurrences of the target string (replaceWhat) within the Word document. It iterates through the text elements of the document's paragraphs and identifies the start and end positions of each occurrence of the target string. It returns a list of WordMatchedPhrase objects representing these occurrences.

The code employs various variables to keep track of the positions and occurrences of the target string within the document. It uses nested loops and conditionals to traverse through the document's text elements and identify matches.

Above code provides functionality to find and replace text efficiently within a Word document using Open XML in C#.

Step 3:Use above class for replacing text

Copy and paste the following code when you click the button.If you're interested in adding new rows to an existing Word document table, please read the article below."

How to add new rows to an existing word document table in C#

 private void button1_Click(object sender, EventArgs e)
        {
// original template path
var inputFile = @"E:\Projects\WordDocument\WordDocument\WordFile\Template.docx";
//modify template path where we save modify word template
var outputFile = @"E:\Projects\WordDocument\WordDocument\WordFile\ModifyTemplate.docx";

//check if file exist or not
if (System.IO.File.Exists(inputFile))
            {
                WordDocumentService wordDocumentService = new WordDocumentService();
if (System.IO.File.Exists(inputFile))
                {
using (WordprocessingDocument doc = WordprocessingDocument.Open(inputFile, true)) //open source word file
                    {
                        Document document = doc.MainDocumentPart.Document;
                        OpenXmlPackage res = doc.SaveAs(outputFile); // copy it to outfile path for editing
                        res.Close();
                    }

using (WordprocessingDocument doc = WordprocessingDocument.Open(outputFile, true)) // open word document and modify it
                    {
                        wordDocumentService.ReplaceStringInWordDocumennt(doc, "«Company_Name»", "Mark Henry");
                        wordDocumentService.ReplaceStringInWordDocumennt(doc, "«Customer_Name»", "Rattlesnake Canyon Grocery");
                        wordDocumentService.ReplaceStringInWordDocumennt(doc, "«Customer_email»", "[email protected]");
                        wordDocumentService.ReplaceStringInWordDocumennt(doc, "«Custome_phone»", "4324343");
                        wordDocumentService.ReplaceStringInWordDocumennt(doc, "«Custome_zipcode»", "67000");
                        wordDocumentService.ReplaceStringInWordDocumennt(doc, "«Customer_address»", "Avda. de la Constitución 2222");
                    }
                }

            }
        }


  • Original Template Path: the path to the original Word document template file (Template.docx) stored on the local file system.
  • Modified Template Path: specifies the path where the modified Word document template file (ModifyTemplate.docx) will be saved after making changes.
  • Check if File Exists: This if statement checks if the original template file exists at the specified path before proceeding with any operations.
  • WordDocumentService Initialization: An instance of the WordDocumentService class is created to utilize its methods for finding and replacing text in the Word document.
  • Open Original Word Document: The original Word document (Template.docx) is opened for editing using the WordprocessingDocument.Open method. It's opened in write mode (true).
  • Save Copy of Original Document: The original document is saved as a copy to the specified output file path (ModifyTemplate.docx). This is done using the SaveAs method of WordprocessingDocument, and the resulting package is stored in the res variable.
  • Close Original Document: The original document (Template.docx) is closed using the Close method on the res package.
  • Open Modified Word Document: The copied Word document (ModifyTemplate.docx) is opened for further modification using the WordprocessingDocument.Open method.
  • Replace Text in Document: Multiple calls are made to the ReplaceStringInWordDocumennt method of the WordDocumentService class to replace placeholders like "«Company_Name»", "«Customer_Name»", etc., with actual values.For example, "«Company_Name»" is replaced with "Mark Henry", "«Customer_Name»" is replaced with "Rattlesnake Canyon Grocery", and so on.
  • Closing Modified Document: After the modifications are done, the modified Word document is closed.

This is code show you how to open an original Word document template, make modifications to it, and save the modified version to a new file. It uses the WordDocumentService class to handle the text replacement process efficiently.

Now let’s run project and hit button. and open output word file , we can replace text.

OutputWordTemplate

 

* if you have a question please comment.

Why we used word template in our Project

Friends, we all keep a lot of application software, programs, tools, etc. on our computer to do the tasks we need like- Photoshop, Tally, Video Editor etc. One of the most important programs for all of us is MS Word (Microsoft Word) which is a program in the package of Microsoft Office.

MS Word has been ruling everyone’s computer for years because it has a unique feature, be it features, interface or usability, it is at the forefront.

MS Word is a program used by every user, in which many types of small and big tasks related to word processing can be done.

Whether it is a matter of typing something or creating an advanced or long document, booklet, resume etc., you can do it very easily in Microsoft Word. To perform such tasks, many functions, tools, etc. are provided inside MS Word, with the help of which very advanced and attractive documents can be created.

Talking about usage, as we have known that MS Word is a word processor program and the job of a word processor program is to prepare, edit, format textual documents, etc., so this simply means that Microsoft Word also Will be doing work-related to documentation.

Feature of MS Word

In MS Word, apart from creating documents, Resume, Newsletter, Report etc., we can also do Editing and Formatting. To do all these tasks, many tools and features are given inside it.

  • Being a user-friendly program, it is very easy to work on it.
  • There are many tools and options for document formatting in this.
  • Various features of MS Word allow us to add Border, Shading, Table, Graph, Chart, Picture, 3D Effect etc. along with text in the document, which makes the document more attractive in Word.
  • There is no risk of spelling mistakes in this as it has the option of turning the Autocorrect feature on or off.
  • It also has a Mailing feature, with the help of which we can mail our document to many people at once.
  • The new version of Microsoft Word also provides the facility to edit PDF files.
  • Microsoft Word allows us to save the file created in it in many formats.