The following is the code I'm using to create a new word document from an existing document. What does work is that it successfully reads the template document (templateName) and it is able to create the 'customXML' string from the model class. But what is not working is the customXML information (address, city, state, zip,...) is not replacing the empty tags.
I pulled this code from an older .NET web application and I'm using it in MVC 4.5 with OpenXml 2.5. The Older version of the code works but not in the MVC version.
public void CreateDocument(Customer customer, string templateName, string documentPath)
{
// Need to create an in memory resizable byte array for loading the county template
byte[] byteArray = File.ReadAllBytes(templateName);
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray, 0, (int)byteArray.Length);
// Open the in memory Open XML document for processing
//using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templateName, true))
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
// Build XML file from the Data Class that will be populated from data entered
// into the Add Customer screen.
// THIS CODE WORKS - A VALID XML STRING IS CREATED
string customXML = BuildCustomXmlPartFromDataClass(customer);
// Replace Custom XML portion of Open XML Package document
// THE mainPart.CustomXmlParts IS NOT NULL
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
if (mainPart.CustomXmlParts != null)
{
mainPart.DeleteParts<CustomXmlPart>(mainPart.CustomXmlParts);
}
CustomXmlPart customXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
using (StreamWriter ts = new StreamWriter(customXmlPart.GetStream())) ts.Write(customXML);
}
// Save the in memory byte array to disk using a FileStream
using (FileStream fileStream = new FileStream(documentPath, System.IO.FileMode.Create))
{
mem.WriteTo(fileStream);
}
// NEW DOCUMENT IS CREATED BUT IT DOES NOT CONTAIN ANY OF THE INFORMATION FROM THE MODEL CLASS
}
}
protected string BuildCustomXmlPartFromDataClass(Customer customer)
{
// Serialize the Data Class to XML
System.Xml.XmlDocument doc = new XmlDocument();
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializercustomer.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
try
{
serializer.Serialize(stream, customer);
stream.Position = 0;
doc.Load(stream);
return doc.InnerXml;
}
catch
{
throw;
}
finally
{
stream.Close();
stream.Dispose();
}
}
There are no errors and a new document is created but it does not contain any information from the Model class (customer). I have seen similar posts but the solution(s) did not work.