Thursday, 18 June 2015

Export to Excel in Microsoft Dynamics AX 2012

Here is the code/job: Hope it helps

static void CreateExcel(Args _args)
    {
       SysExcelApplication  xlsApplication;
       SysExcelWorkBooks    xlsWorkBookCollection;
       SysExcelWorkBook     xlsWorkBook;
       SysExcelWorkSheets   xlsWorkSheetCollection;
       SysExcelWorkSheet    xlsWorkSheet;
       SysExcelRange        xlsRange;
       CustTable            custTable;
       int                  row = 1;
       str                  fileName;
   
       //Filename
       fileName = "D:\\test.xlsx";
       //Initialize Excel instance
       xlsApplication           = SysExcelApplication::construct();
       //Open Excel document
       //xlsApplication.visible(true);
       //Create Excel WorkBook and WorkSheet
       xlsWorkBookCollection    = xlsApplication.workbooks();
       xlsWorkBook              = xlsWorkBookCollection.add();
       xlsWorkSheetCollection   = xlsWorkBook.worksheets();
       xlsWorkSheet             = xlsWorkSheetCollection.itemFromNum(1);
       //Excel columns captions
       xlsWorkSheet.cells().item(row,1).value("Field name1");
       xlsWorkSheet.cells().item(row,2).value("FieldName2");
       row++;
       //Fill Excel with CustTable AccountNum and Name fields (only 20 records)
       while select #FieldName1,#FieldName2 from #tableName
       {
          if(row == 20)
            break;
          xlsWorkSheet.cells().item(row,1).value(#FieldName1);
          xlsWorkSheet.cells().item(row,2).value(#FieldName2 );
          row++;
       }
       //Check whether the document already exists
       if(WinApi::fileExists(fileName))
          WinApi::deleteFile(fileName);
       //Save Excel document
       //xlsWorkbook.saveAs(fileName);
       //Open Excel document
       xlsApplication.visible(true);
   
       //Close Excel
       //xlsApplication.quit();
       //xlsApplication.finalize();

    }

No comments:

Post a Comment