Connecting Microsoft.Office.Interop.Word with DocumentOpenXml

230 Views Asked by At

I have to copy selected text from activedocument to new file (at the end of target file). Both (source and target) are docx files. The source file is opened in Word and the user is working with it.

I would like to copy the selection without opening the target file as Microsoft.Office.Interop.Word.Document and copy-paste (for performance reasons). I don't know how to change the "Selection" in open document to xml understandable by DocumentOpenXml and how to inject this xml into target file.

using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using Range = Microsoft.Office.Interop.Word.Range;


public void RangeToNewDocument(string documentPath, Range range)
{

    string selectedXML = range.WordOpenXML; //??????????
    using (WordprocessingDocument doc = WordprocessingDocument.Open(documentPath, true))
    {
        Body body = doc.MainDocumentPart.Document.Body;

        //body.Append(selectedXML); ??????

        doc.SaveAs(documentPath + ".RangeToNewDocumentTest.docx");
    }
}

Many example codes are for "How to add something" but there are new objects (as 'Runs' or all 'Paragraphs') but I couldn't find anything about an existing object. The only link I found is: https://learn.microsoft.com/en-us/office/open-xml/how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif

but there replace one ThemePart with another and I have no idea how to adjust it for me.

0

There are 0 best solutions below