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.
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
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.
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");
}
}
}
}
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.
* if you have a question please comment.
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.
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.