Saturday, December 17, 2016

AX 2012 X++ code to import from EXCEL files COMVARIANT Vikas Mehta

static void readExcelFile(Args _args)
{
    SysExcelApplication         application;
    SysExcelWorkbooks           workbooks;
    SysExcelWorkbook            workbook;
    SysExcelWorksheets          worksheets;
    SysExcelWorksheet           worksheet;
    SysExcelCells               cells;
    Filename                    filename;
    COMVariantType              type;
   
int                         rowNo;
    SampleTable       SampleTable;
    str COMVariant2Str(COMVariant _cv,
int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
    {
       
switch (_cv.variantType())
        {
           
case (COMVariantType::VT_BSTR):
           
return _cv.bStr();
           
case (COMVariantType::VT_R4):
           
return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);
           
case (COMVariantType::VT_R8):
           
return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);
           
case (COMVariantType::VT_DECIMAL):
           
return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);
           
case (COMVariantType::VT_DATE):
           
return date2str(_cv.date(),123,2,1,2,1,4);
           
case (COMVariantType::VT_EMPTY):
           
return "";
           
default: throw error(strfmt("@SYS26908", _cv.variantType())); } return "";
    }
rowNo   = 2;//If the excel file having header.
application = SysExcelApplication::construct();
workbooks = application.workbooks();
filename = @"C:\temp";//Excel file path.
try
    {
        workbooks.open(filename);
    }
   
catch (Exception::Error)
    {
       
throw error("File cannot be opened.");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
type = cells.item(rowNo, 1).value().variantType();
while (type != COMVariantType::VT_EMPTY)
    {
        type = cells.item(rowNo+1, 1).
value().variantType();
SampleTable.clear();
SampleTable.MainAccountId = COMVariant2Str(cells.item(rowNo, 1).value());

SampleTable.insert();
rowNo++;//To get next column number in the loop.
    }
info('fim');
application.quit();
}



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...