How to create an excel file in Dyn365 F&O with x++

In Dynamics 365 Finance and Operation it is easy to create an excel file with x++. To do this you can use the following code snippet:

using OfficeOpenXml;

internal final class CreateExelFile_RunnClass
{
    /// <summary>
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
        {
            using (var package = new ExcelPackage(stream))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
                //header
                ExcelRange cel11 = worksheet.Cells.get_Item(1,1);
                cel11.Value = 'Header Field1';
                ExcelRange cel12 = worksheet.Cells.get_Item(1,2);
                cel12.Value = 'Header Field2';
                ExcelRange cel13 = worksheet.Cells.get_Item(1,3);
                cel13.Value = 'Header Field3';

                int row = 2;

                //row
                CustTable custTable;

                while select custTable
                {
                    ExcelRange cellVal1 = worksheet.Cells.get_Item(row,1);
                    cellVal1.Value = custTable.AccountNum;

                    ExcelRange cellVal2 = worksheet.Cells.get_Item(row,2);
                    cellVal2.Value = custTable.CustGroup;

                    ExcelRange cellVal3 = worksheet.Cells.get_Item(row,3);
                    cellVal3.Value = custTable.name();

                    row++;
                }
                         
                package.Save();
            }
            File::SendFileToUser(stream, 'Table.xlsx');
        }
    }
}

Lascia un commento