web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :

How to generate and populate data to Word documents using OpenXML and X++ in Dynamics 365 for Operations

Hichem.Chekebkeb Profile Picture Hichem.Chekebkeb 3,371

I was lately trying to find a better and easier way to populate data to word documents from Microsoft Dynamics AX to Word documents, instead of using bookmarks.

I experimented OpenXML library and got pretty good results, yet subject to enhancement.

Below the steps:

1-      Create a new Word document (acts like a template)

2-      Enable Developer Tab in Word from Options > Customize Ribbon > Checked Developer

Capture1.PNG

3-      Add TextFields and put their names (ex: BookName) as text

Capture2.PNG

Capture3.PNG

4-      Download the OpenXML library in Visual Studio using Nuget and any .Net project then grab the assembly and reference it to your D365FO project.

Capture.PNG

Capture22.PNG

Capture222.PNG

5-      Use the following code to create a copy of the template and replaces the existing text with the actual you one you want to populate.

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml;

using System.Collections;

 

class WordFieldsSample

{       

    public static void main(Args _args)

    {   

        str                     sourcePath= @"\\SourceFolder\SampleTemplate.docx";

        str                     destinationPath = @"\\DestinationFolder\SampleInstance.docx"

        if (sourcePath&& System.IO.File::Exists(sourcePath))

        {

            if(System.IO.File::Exists(destinationPath ))

                System.IO.File::Delete(destinationPath );

            System.IO.File::Copy(sourcePath,destinationPath );

        }

 

        using(WordprocessingDocument document =  WordprocessingDocument::Open(destinationPath, true))

        {

            document.ChangeDocumentType(WordprocessingDocumentType::Document);

            Wordprocessing.Text item = new DocumentFormat.OpenXml.Wordprocessing.Text();

            var allControls =  document.MainDocumentPart.Document.Descendants();

            var enum = allControls .getEnumerator();

            while (enum.moveNext())

            {

                if(enum.Current.GetType().Equals(item.GetType()))

                {

                    item = enum.Current;

                    if (item.Text == "BookName")

                           item.Text = "My sample book";

                }

            }

            document.Save();

            document.Close();

        } 

    }

 

}

Hope it helps!

Comments

*This post is locked for comments