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#
- Simple Way Find and replace text in Word document using C#
- Implementing “Remember Me” Feature in ASP.NET MVC
- [Solved]-Cookie loses value when page is changed in MVC
- How to post File Upload and other form fields to one action Asp .Net MVC C#
- How To Post File and Data to API using HttpClient C#
- Create ASP.NET Core Web API Without Entity Framework
- .NET Core Web API Using Code First Entity Framework Approach
- Create Asp.Net Core Web Api Using Entity Framework Database First
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- CRUD operation using partial view in MVC with modal popup
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- Crud Operations in MVC Without Entity Framework
- Create Login,Signout and Registration in Asp .Net Mvc Using Entity
- Export Gridview to Excel and Csv in Asp .Net With Formatting Using c#
- How to Display Binary Image in Gridview from Database in Asp .Net c#
- [Solved]-How to Upload pdf file using jquery MVC?
- [Solved]-Uploading both data and files in FormData using Ajax MVC
- C# -Saving a base64 string as an image into a folder on server in Web Api
- [Solved]-Download pdf file from link and save in local file folder in Asp .Net
- [Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET
- [Solved]-LEFT OUTER JOIN in LINQ With Where clause in C#
- INNER JOIN,RIGHT JOIN,LEFT JOIN USING LINQ IN Multiple Table C#
- [Solved]-Convert Base64 To Image And Save in folder and Display it- C#
- [Solved]-How to Overlay Two Images in .NET-C#
- How to Create Multilingual Website in Asp .Net
- C# – How to add double quotes to a string that is inside a variable
- Update an Image with Upload Button For Each Row in Gridview-Asp .Net
- How to Bind Data in DataList Control in Asp.Net – C#
- Upload and Display an Image in Gridview From Image Path in Database -C#