Reputation: 197
I'm trying to insert some information and some pictures from a database into a Word Document.
I have created a Word document to serve as a template where I want to find and replace the keywords with the actual data and picture.
How do I open this template, replace the keywords, and put it into the new document. Then I need to re-open that template and do it again until everyone in the List is inside the new Word document.
//The template file exists, so open it and use it to set up the main Word document
using (WordprocessingDocument templatePackage = WordprocessingDocument.Open(templateDocPath, false))
{
//Read the template file
string docText = null;
using (StreamReader sr = new StreamReader(templatePackage.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
string tempString = docText;
Regex regexText = new Regex("<name>");
docText = regexText.Replace(docText, tnlCampers[0].FirstName + " " + tnlCampers[0].LastName);
regexText = new Regex("<address>");
docText = regexText.Replace(docText, tnlCampers[0].Address1 + " " + tnlCampers[0].Address2 + " " + tnlCampers[0].City + ", " + tnlCampers[0].State + " " + tnlCampers[0].ZipCode);
regexText = new Regex("<phone>");
docText = regexText.Replace(docText, tnlCampers[0].CellPhone);
regexText = new Regex("<email>");
docText = regexText.Replace(docText, tnlCampers[0].Email);
//Write to the newly created Word Document
using (StreamWriter sw = new StreamWriter(package.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
But when I do a foreach loop on my tnlCampers list it throws an error because it's trying to copy the full document structure instead of just the body part. What can i do?
Upvotes: 1
Views: 1602
Reputation: 669
you might also try our GemBox.Document component.
It has very user friendly and efficient support for mail merge. See C# Word mail merge article and customize mail merge sample.
Upvotes: 0
Reputation: 2132
You can try Word Doc Generator which is an utility to generate Word documents from templates using Visual Studio 2010 and Open XML 2.0 SDK.
Upvotes: 1