Thursday, 20 February 2014

Import Data from Excel File in AX 2012

static void importRecord(Args _args)
{
SysExcelApplication xlsApplication;
SysExcelWorkBooks xlsWorkBookCollection;
SysExcelWorkBook xlsWorkBook;
SysExcelWorksheets xlsWorkSheetCollection;
SysExcelWorksheet xlsWorkSheet;
SysExcelRange xlsRange;
SysExcelCells Cells;
SysExcelCell RCell;
CommaIO inFile;
int nRow,i;
DialogField dialogPath;
Dialog dialog;
Filename filename;
Name Name;
ID ID;
Phone Phone;
income income;
importrecord exportImportRecords; //Table used to store data
;
dialog = new Dialog(“Import”);
dialogPath = dialog.addField(extendedTypeStr(Filenameopen), “File Name”);
dialog.run();
if (dialog.run())
{
filename = (dialogPath.value());
}
inFile = new CommaIO (filename, ‘R’);
if (!inFile || infile.status() != IO_Status::Ok )
{
throw error (strfmt(“@SYS19312″,filename));
}
try
{
xlsApplication = SysExcelApplication::construct();
xlsWorkBookCollection = xlsApplication.workbooks();
xlsWorkBookCollection.open(filename);
xlsWorkSheetCollection = xlsApplication.worksheets();
xlsWorkSheet = xlsWorkSheetCollection.itemFromNum(1);
Cells = xlsWorkSheet.Cells();
nRow = 2;
RCell = Cells.Item(nRow, 1);
while (RCell.value().bstr() != “”)
{
ID = any2int(RCell.value().bStr());
RCell = Cells.item(nRow,2);
Name = RCell.value().bStr();
RCell = Cells.item(nRow,3);
Phone = RCell.value().bStr();
RCell = Cells.item(nRow,4);
income = any2real(RCell.value().bStr());
exportImportRecords.ID = ID;
exportImportRecords.Name = Name;
exportImportRecords.Phone = Phone;
exportImportRecords.income = income;
exportImportRecords.insert();
nRow++;
RCell = Cells.Item(nRow, 1);
}
xlsApplication.quit ();
xlsApplication.finalize ();
info(“Import completed”);
}
catch( Exception::Error)
{
xlsApplication.quit ();
xlsApplication.finalize ();
ttsabort;
info(“Unable to process the excel import “);
}
}

No comments:

Post a Comment