Search code examples
c#comvstooffice-interopcom-interop

VSTO Office Interop: Manipulating Office XML at Run-Time


Working with Office's XML files can sometimes be a convenient way of quickly manipulating a document.

I.e. searching through the ZIP data of a PowerPoint file and changing the XML within the file.

I wonder if there is a way to access and manipulate a document's (PowerPoint, or otherwise) XML from within a VSTO Add-In and have the changes be reflected in the currently opened document in real-time? (E.g. when replacing a string).

I am looking for a solution that does not require the document to be re-opened.

The answer may well be that this is not possible/supported since I could not find official documentation in the Office Interop API.


Solution

  • This should do the job, but keep in mind even if it does not require to reopen the document, the full content of the document is reloaded ... for a huge documents it will be slow.

    For the example i am using Word document.

    var wordDocument = app.ActiveDocument;
    var openXmlFormattedStr = wordDocument.Content.WordOpenXML;
    var manipulatedOpenXmlFormattedStr = .....; // do something with the xml
    wordDocument.Content.InsertXML(manipulatedOpenXmlFormattedStr, null);
    

    EDIT 2017-12-15: Power Point and Excel interop does not expose direct access to the open xml format. The only way is to use .SaveAs with the appropriate openxml format and then read the content from the file system.