Tuesday, 13 May 2014

Copying Data from excel sheet to AX Tables


Hi friends,today i have written a simple code which can help you import data from excel sheet into ax table
The below code will help you achieve the task:
I have created a simple table named mynames in the AOT with fields Fname,Lname and salary.My excel sheet is also named mynames.xlsx. The below code helped me to achieve the task.


static void mynamescopyfromexcel(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;

SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
myNames  mynames;

int row = 1 ;

str lastname;
str firstname;
    int salary;
;

application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename = "F:\\mynames.xlsx";
try
{
workbooks.open(filename);

}
catch (Exception::Error)
{
throw error("File cannot be opened.");
}


    workbook = workbooks.item(1);
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(1);//.itemFromName("Sales target");
cells = worksheet.cells();

do
{
row++;


firstname = cells.item(row, 1).value().bStr();
lastname = cells.item(row, 2).value().bStr();
    salary = any2int(cells.item(row,3).value().toString());
    mynames.clear();
    mynames.Fname = firstname;
    mynames.Lname = lastname;
    mynames.Salary = salary;
    mynames.insert();

    info("Data inserted succesfully");




type = cells.item(row+1, 1).value().variantType();
}

while (type != COMVariantType::VT_EMPTY);
application.quit();
}

3 comments:

  1. Have always wanted to know this. I we'll have time from this month you take me through

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. thankyou very much
    Is it possible to import one file , and insert respective records into 2 different tables??

    ReplyDelete