Sometimes you may want to generate a Word document from code in D365FO, which gives you much more control over the result than if you simply printed a report to Word.
Here is a very brief example of how you can do it.
Start with creating an X++ project. Then add a C# class library to the same project. Right-click the C# project, use Manage NuGet Packages… and install DocumentFormat.OpenXml package.
Then add the following class:
usingSystem.IO;usingDocumentFormat.OpenXml;usingDocumentFormat.OpenXml.Packaging;usingDocumentFormat.OpenXml.Wordprocessing;
namespace WordLib
{publicclass WordDoc
{public Stream Create(){
MemoryStream ms =new MemoryStream();
using(WordprocessingDocument wordDocument =
WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document, true)){
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
string text ="Do androids dream of electric sheep?";
Body body =new Body(new Paragraph(new Run(new Text(text))));
mainPart.Document=new Document(body);}
return ms;}}}
This code will create a very simple Word document, containing only a single line of text, and returns it as a memory stream. You would likely need something more complicated, but that’s out of scope of this blog post. You can get more information from Open XML SDK documentation.
Build the C# class library and we’re done with it; now we need to call it from X++.
Go to the X++ project, right-click References, chose Add Reference… and add a project reference to the C# library.
Then add a runnable class with the following code, which merely calls the library and returns the stream as a file to user:
class WordDocGeneratorSample
{publicstaticvoid main(Args _args){
using (System.IO.Stream wordStream =new WordLib.WordDoc().Create()){
File::SendFileToUser(wordStream,'file.docx');
}}}
Set the class as the startup object, run the project and your browser should offer you the Word document for download.