March 19, 2015

X++ code to create Excel file in AX 2009

static void CreateExcelDocument (Args _args)
 {
    SysExcelApplication xlsApplication;
    SysExcelWorkBooks xlsWorkBookCollection;
    SysExcelWorkBook xlsWorkBook;
    SysExcelWorkSheets xlsWorkSheetCollection;
    SysExcelWorkSheet xlsWorkSheet;
    SysExcelRange xlsRange;
    CustTable custTable;
    int row = 1;
    str fileName;
    ;

    // Name of the Excel document.
    fileName = "C:\\test.xslx";

    // Excel open and initialize.
    xlsApplication = SysExcelApplication:: construct ();
    xlsApplication.visible (true);

    // Create an Excel Worksheet produce.
    xlsWorkBookCollection = xlsApplication.workbooks();
    xlsWorkBook = xlsWorkBookCollection.add();
    xlsWorkSheetCollection = xlsWorkBook.worksheets();
    xlsWorkSheet = xlsWorkSheetCollection.itemFromNum (1);

    // Write to the worksheet cells headings.
    xlsWorkSheet.cells (). item (row, 1). value ('Account Number');
    xlsWorkSheet.cells (). item (row,2). value ('name');

    row ++;

    // Excel Worksheet with data fill / (Excel cells fill).
    while select custTable
    {
    xlsWorkSheet.cells (). item (row, 1). value (custTable.AccountNum);
    xlsWorkSheet.cells (). item (row, 2). value (custTable.Name);
    row ++;
    }

    // Check whether the document already exists.
    if (WINAPI:: fileExists (fileName))
    {
    Winapi:: DeleteFile (fileName);
    }

    // Save Excel document.
    xlsWorkbook.saveAs(fileName);

    // Close Excel.
    xlsApplication.quit ();
    xlsApplication.finalize ();
 }

No comments:

Post a Comment