Tuesday, April 3, 2012

How to write data into an Excel sheet from Microsoft Dynamics Ax

This article explains
  • How to write data into an Excel sheet from Microsoft Dynamics Ax using X++ language.
  • How to write data into an Excel sheet using COM object in Microsoft Dynamics Ax.
  • How to export Microsoft Dynamics Ax data into an Excel sheet at run time / dynamically /programmatically using X++ language.
I applied it on Dynamics Ax 2009.
Prerequisite:

  • You should have X++ basic programming knowledge;
Open Ax client > AOT > Jobs node, create a new job and copy the below code segment into your job.
static void writeDataIntoExcelSheetFromAx(Args _args)
{
InventTable inventTable;
Container itemIdCon;
COM comRange;
COM comWorkBook;

COM comWorkBooks;
COM comWorkSheet;
COM comCharacters;
COM comAppl;
str test,test1;
int offset = 65-1; //65 means letter 'A'
str 2 columnId;
str fileName;
str time;
int i;
#define.Excel('Excel.Application')
;

comAppl = new COM(#Excel);
comAppl.visible(true);
comWorkbooks = comAppl.workbooks();
WINAPI::createFile('C:\\test.xls');
comWorkbook = comWorkbooks.open('C:\\test.xls',true,true);
comWorksheet = comWorksheet.new('C:\\test.xls');
comWorksheet = comWorkbook.activeSheet(); //Use comWorkbook.activateSheet(); in case of Ax 3.0
comWorksheet.select();

while select inventTable
{
columnId = num2char(offset + 1);
i++;
test = columnId + int2str(i);
comRange = comWorksheet.range(test);
comCharacters = comRange.characters();
comCharacters.insert(inventTable.ItemId);

columnId = num2char(offset + 2);
test = columnId + int2str(i);
comRange = comWorksheet.range(test);

comCharacters = comRange.characters();
comCharacters.insert(inventTable.ItemName);
}

WINAPI::createDirectory('C:\\AxData');
time = time2str(timenow(),1,1);
time = strrem(time,':');
fileName = 'C:\\AxData\\' + curuserid() + date2str(today(),123,2,0,3,0,4)+ time + 'test' + '.xls';
comWorkbook.saveAs(fileName);
}

3 comments:

  1. HI Kishore,

    I am Pavan, new to dynamics ax. I was trying the above code and changed the path of excel file, as "C:\\Users\PAVE101\Desktop\test.xlsx", but i am getting error like "est.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct."

    ReplyDelete
  2. You have to change path of excel file in each line of code where path is exist.
    Please check the same.

    ReplyDelete
  3. Hi Kishore,
    Thanks for your support, I need your similar support throughtout my career.
    Thanks for your Blog, Its very good.
    I found the error ie. In path we need to specify like this "'c:\\Users\\PAVE101\\Downloads\\empl_rep.xlsx'"

    ReplyDelete