question

PaulRyan-4569 avatar image
PaulRyan-4569 asked ·

In UWP How to open MS Word docs for mail merge

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

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

FayWang-MSFT avatar image
FayWang-MSFT answered ·

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 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.

Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

PaulRyan-4569 avatar image
PaulRyan-4569 answered ·

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

Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.