简体   繁体   中英

Creating a Microsoft Word Interop Document from Open Xml Document

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();
    }
  }
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM