Simple Way Find and replace text in Word document using C#

Recently I’m working on a project in which I need to implement the Find And Replace Text In Word Document Using C#. Our project requirement is that our software can have multiple standard templates in word format.

So users can download it and can modify it and can re-use it for printing and on click on the print button, we need to fill the same data in the template and then the customer can download it.

So I have used the open XML for finding and replacing text in the word document. you can also interop for the same purpose. but I find open XML is more convenient for me so I have used open XML for my task.

I am going to discuss how we can Edit Word documents using OpenXML C#, so let’s start.

We have created windows from the project. onClick of the button we going to 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;

        }

    }
}

Step 3:Use above class for replacing text

copy the paste the below code on button click

if you are looking for adding new rows to an existing word document table in then please read below article

 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");
                    }
                }

            }
        }

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.

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Your Header Sidebar area is currently empty. Hurry up and add some widgets.