In UWP How to open MS Word docs for mail merge

Paul Ryan 316 Reputation points
2020-06-09T13:27:01.227+00:00

Hi,

Can someone please tell me how I can open MS Word documents when working in UWP. I do not want to open Word App, I want to open a word document in the background, to edit and save it as a Word document . I see Exceed has a package, that looks pretty simple, but I cannot figure out how to get "DocX.Load...." to work, as I understand I need to use "StorageFile" with UWP.

If there is a better method I am open to it

thanks for the help
Paul

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Fay Wang - MSFT 5,191 Reputation points
    2020-06-10T02:51:31.397+00:00

    Hello,

    Welcome to Microsoft Q&A!

    MS Word documents are different from regular text files, so the Storage apis can't directly read or edit the text for you. You could try to use the Open XML SDK to achieve it, before using it, you need to install the DocumentFormat.OpenXml nuget package. Then using WordprocessingDocument.Open(Stream stream, bool isEditable) method to create a instance of WordprocessingDocument and edit the text in it. Here are some scenarios for [Word Document] (https://learn.microsoft.com/en-us/office/open-xml/word-processing?redirectedfrom=MSDN) you can check it. I will take an example of opening a document and adding new text as an example:

    private async void Button_Click(object sender, RoutedEventArgs e)  
    {  
        StorageFolder f = KnownFolders.PicturesLibrary;  
        StorageFile sampleFile = await f.GetFileAsync("New Microsoft Word Document.docx");  
        string strTxt = "Append text in body - OpenAndAddTextToWordDocument";  
        Stream randomAccessStream = await sampleFile.OpenStreamForWriteAsync();  
    
        OpenAndAddTextToWordDocument(randomAccessStream, strTxt);  
    }  
    
    public static void OpenAndAddTextToWordDocument(Stream stream, string txt)  
    {  
        // Open a WordprocessingDocument for editing using the stream.  
        WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, true);  
    
        // Assign a reference to the existing document body.  
        Body body = wordprocessingDocument.MainDocumentPart.Document.Body;  
    
        // Add new text.  
        Paragraph para = body.AppendChild(new Paragraph());  
        Run run = para.AppendChild(new Run());  
        run.AppendChild(new Text(txt));  
    
        // Close the handle explicitly.  
        wordprocessingDocument.Close();  
    }  
    

    Thanks.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Paul Ryan 316 Reputation points
    2020-06-10T16:46:21.82+00:00

    thanks for the reply very helpful
    Was able to get it to work using DocX by Xceed

    0 comments No comments