Reputation: 607
Trying to create an interop app from an open xml file. I'm using reflected code of a word file from Open Xml SDK. When i'm trying to insert xml of the Open Xml Document into interop document
doc.Range().InsertXML(package.MainDocumentPart.Document.OuterXml);
this line throws System.Runtime.InteropServices.COMException
which says XML cannot be inserted into that location.
Here is the full code
public void CreatePackage()
{
using (MemoryStream mem = new MemoryStream())
{
using (WordprocessingDocument package = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document))
{
CreateParts(package);
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
doc.Range().InsertXML(package.MainDocumentPart.Document.OuterXml);
doc.Activate();
}
}
}
Upvotes: 2
Views: 3275
Reputation: 385
You can do like this :
public void CreatePackage()
{
using (MemoryStream mem = new MemoryStream())
{
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document))
{
CreateParts(wordDocument);
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
XDocument xDoc = OPCHelper.OpcToFlatOpc(wordDocument.Package);
string openxml = xDoc.ToString();
doc.Range().InsertXML(openxml);
doc.Activate();
}
}
}
To get the code of OPCHelper
Class You can take it from here Utility to generate Word documents from template.
For more information Look at this one also Transforming Open XML Documents to Flat OPC Format
Upvotes: 1
Reputation: 11903
I would save the OpenXML to a temp file and use interop to open that file in Word. But I don't know if interop should or does support XML so I can't answer why InsertXML doesn't work. I suspect it doesn't expect OpenXML kind of XML, but something else.
Upvotes: 0