How to generate and populate data to Word documents using OpenXML and X++ in Dynamics 365 for Operations
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
3- Add TextFields and put their names (ex: BookName) as text
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.
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!

Like
Report
*This post is locked for comments