Showing posts with label Excel to AX 2012. Show all posts
Showing posts with label Excel to AX 2012. Show all posts

Friday, 22 February 2013

Import From Excel File Using X++ in AX 2012



Here is the code snippet for importing data from Excel in AX 2012.
In this example I have a ProductType table with fields (ID, ProductType ,Description )

static void ProductType(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
ProductType productType;
int row;
int _productTypeId;
str _productType;
str _description;
;

application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename = "Path\\filename.xlsx";
try
{
workbooks.open(filename);
}
catch (Exception::Error)
{
throw error("File cannot be opened.");
}

workbook = workbooks.item(1);
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(4); //Here 3 is the worksheet Number
cells = worksheet.cells();
do
{
row++;
_productTypeId = any2int(cells.item(row, 1).value().toString());
_productType = cells.item(row, 2).value().bStr();
_description = cells.item(row, 3).value().bStr();

productType.ID = _productTypeId;
productType.ProductType = _productType;
productType.Description = _description;
productType.insert();

type = cells.item(row+1, 1).value().variantType();
}
while (type != COMVariantType::VT_EMPTY);
application.quit();
}