Monday 29 October 2018

Export data into Excel using X++ code in D365 F&O / AX 7

Below is the quick code snippet to export the data to excel/create an excel in AX 7/D365 for operations
Please note, in D365 we can achieve this through OfficeOpenXml namespace
Improvise it based on your requirement
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table;
class SRWriteToExcel
{
    public static void main(Args _args)
    {
        CustTable custTable;
        MemoryStream memoryStream = new MemoryStream();

        using (var package = new ExcelPackage(memoryStream))
        {
            var currentRow = 1;

            var worksheets = package.get_Workbook().get_Worksheets();
            var CustTableWorksheet = worksheets.Add("Export");
            var cells = CustTableWorksheet.get_Cells();
            OfficeOpenXml.ExcelRange cell = cells.get_Item(currentRow, 1);
            System.String value = "Account Number";
            cell.set_Value(value);
            cell = null;
            value = "Currency";
            cell = cells.get_Item(currentRow, 2);
            cell.set_Value(value);

            while select CustTable
            {
                currentRow ++;
                cell = null;

                cell = cells.get_Item(currentRow, 1);
                cell.set_Value(CustTable.AccountNum);
                cell = null;

                cell = cells.get_Item(currentRow, 2);
                cell.set_Value(CustTable.Currency);
            }
            package.Save();
            file::SendFileToUser(memoryStream, ‘Test’);
           
        }
       
    }

}

9 comments:

  1. Hi Im getting error in the line package.save()
    specified cast is not valid

    ReplyDelete
    Replies
    1. There should be some issue with the value you passed. e.g. maybe passed date to set_value but expected value will be string.

      Delete
  2. Hi i got the same specified cast is not valid. i removed date values then it works. i need to pass date values as well. how to pass date value to set_Value.?? please reply

    ReplyDelete
  3. How to export data from table to an existing excel file using this code

    ReplyDelete
  4. Hi! Can we write data to already created excel

    ReplyDelete
  5. How to save this report in pdf what is the code

    ReplyDelete

Adding a newline into a string in C# and X++

Below is the sample code we can use for  adding a newline after every occurrence of "@" symbol in the string in C#   using System...