I am using Word and OpenXml to provide mail merge functionality in a C# ASP.NET web application:
1) A document is uploaded with a number of pre-defined strings for s
I second the use of Content Controls recommendation. Using them to mark up the areas of your document where you want to perform substitution is by far the easiest way to do it.
As for duplicating the document (and retaining the entire document contents, styles and all) it's relatively easy:
string documentURL = "full URL to your document";
byte[] docAsArray = File.ReadAllBytes(documentURL);
using (MemoryStream stream = new MemoryStream)
{
stream.Write(docAsArray, 0, docAsArray.Length); // THIS performs doc copy
using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
{
// perform content control substitution here, making sure to call .Save()
// on any documents Part's changed.
}
File.WriteAllBytes("full URL of your new doc to save, including .docx", stream.ToArray());
}
Actually finding the content controls is a piece of cake using LINQ. The following example finds all the Simple Text content controls (which are typed as SdtRun):
using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
{
var mainDocument = doc.MainDocumentPart.Document;
var contentControls = from sdt in mainDocument.Descendants() select sdt;
foreach (var cc in contentControls)
{
// drill down through the containment hierarchy to get to
// the contained object
cc.SdtContentRun.GetFirstChild().GetFirstChild().Text = "my replacement string";
}
}
The
and
elements may not already exist but creating them is a simple as:
cc.SdtContentRun.Append(new Run(new Text("my replacement string")));
Hope that helps someone. :D