Wednesday, March 1, 2017

Import From Excel File Using X++ in AX 2012



In this example i have my customized table ImportTable with the following fields
(itemid,qty,price,purchunit,lineamount)



static void ImportFromExcel(Args _args)
{
Dialog _dialog;
DialogField _file;
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
ImportTable importTable; //Declaring Table Name
int  row = 1;
str   _itemid;
real  _qty;
real  _price;
str   _purchunit;
real  _lineamount;

_dialog = new Dialog("Please select the file to load");
_dialog.addText("Select file:");
_file   = _dialog.addField(ExtendedTypeStr("FilenameOpen"));
_dialog.run();

if (_dialog.closedOK())
{
info(_file.value() );

application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename =_file.value(); //ExcelSheet File Name
try
{
     workbooks.open(filename);
}
catch (Exception::Error)
{
     throw error('File cannot be opened');
}

workbook = workbooks.item(1);
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(1); //Here 1 is the worksheet Number
cells = worksheet.cells();
do
{
        row++;
        _itemid     = cells.item(row, 1).value().bStr();
        _qty         = cells.item(row, 2).value().double();
        _price       = cells.item(row, 3).value().double();
        _purchunit   = cells.item(row, 4).value().bStr();
        _lineamount  = cells.item(row, 5).value().double();

        importTable.ItemId       = _itemid;
        importTable.Qty          = _qty;
        importTable.Price        = _price;
        importTable.PurchUnit    = _purchunit;
        importTable.LineAmount   = _lineamount;
        importTable.insert();
        type = cells.item(row+1, 1).value().variantType();
}
while (type != COMVariantType::VT_EMPTY);
application.quit();
info("Data is Imported");
}
}

2 comments:

  1. Getting this error
    Variable ImportTable has not been declared.

    ReplyDelete
    Replies
    1. Importtable is my Customized Table you need to create you table

      Delete