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.
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.
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»", "Rattlesnakez@gmail.com");
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.
* 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.
The post Simple Way Find and replace text in Word document using C# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- C# Alternate Way to Find and Replace Text in Word Document
- Issue with find and replace apostrophe( ' ) in a Word Docx using OpenXML and Regex
- Word Automation Find and Replace not including Text Boxes
- How to find and replace text in a file
- Two Way Binding to AvalonEdit Document Text using MVVM
- Replace bookmark text in Word file using Open XML SDK
- c# word interop find and replace everything
- Duplicating Word document using OpenXml and C#
- Simple way to compare Dates in DateTime attribute using Entity Framework 4 and Linq queries
- Using Interop.Word, is there a way to do a replace (using Find.Execute) and keep the original text's justification?
- What is the BEST way to replace text in a File using C# / .NET?
- How to Replace [Word] with Word using Regex.Replace and should replace whole word only
- What is a good way to find a specific value in an XML document using C#?
- Save as PDF using c# and Interop not saving embedded pdf in a word document
- How to convert a C# object initializer to use a constructor using Resharper structural find and replace
- Replace text using regular expressions in MS Word - C#
- Simple way to read and write name value text file
- add-in in VSTO - How to get text from Word document using Ribbon with button
- Creating and Editing word document by using a program
- Find and Replace All But Text Between Double Quotes in VS2010
- Find and replace text in excel with specified font name
- How to find the most recent file in a directory using .NET, and without looping?
- Correct Way to Load Assembly, Find Class and Call Run() Method
- Find and return JSON differences using newtonsoft in C#?
- Parsing one terabyte of text and efficiently counting the number of occurrences of each word
- Is there a faster way than this to find all the files in a directory and all sub directories?
- Proper way to Mock repository objects for unit tests using Moq and Unity
- Using Linq to SQL, how do I find min and max of a column in a table?
- Is there a way to check if text is in cyrillics or latin using C#?
- How to find latitude and longitude using C#
- Mongo DB object Id deserializing using JSON serializer
- Cast object to KeyValuePair with "generic value"?
- "Hot Track" effect on a Windows Form UserControl
- Decrypt string using AES/CBC/NoPadding algorithm
- How can i set the caret position to a specific index in passwordbox in WPF
- Autofit Row Height of Merged Cell in EPPlus
- Nullable types and the ternary operator: why is `? 10 : null` forbidden?
- How Can I strip HTML from Text in .NET?
- Cannot implement an interface member because it is not public
- ASP.NET Repeater and DataBinder.Eval
- C#: Formatting Price value string
- MVVM - Does validation really have to be so cumbersome?
- Caching delegate results
- Are there hidden expenses hardcoding data as code in C#?
- The name WebHost does not exists in current context
- Does await completely block the thread?
- How can I determine for which platform an executable is compiled?
- TypeInitializationException: The type initializer for 'vService.CheckService' threw an exception
- EPPLUS To Clear Contents of A Range Of Cells
- async keyword and choice of the TaskScheduler