Monday, January 2, 2012

Read Data from EXCEL Sheet

There are multiple ways to read data from an EXCEL Sheet.
1st method: Reading Excel Data using DataTable


Datatable.Importsheet "path of the excel file.xls", source sheet ID/Name, desination sheet ID/Name
Datatable.SetCurrentRow(1)  'Read Value from First Row
value = datatable.Value(parameterName,Sheet ID/Name)

'To Read Value from All the rows

Datatable.Importsheet "path of the excel file.xls", source sheet ID/Name, desination sheet ID/Name
For vRow = 1 To Datatable.GetRowCount
    Datatable.SetCurrentRow(vRow)
    value = datatable.Value(parameterName,Sheet ID/Name)
Next


2nd method: Reading Excel Data using Excel Object

Dim objexcel, objWorkbook, objDriverSheet, columncount, rowcount
set objexcel = Createobject("Excel.Application")
Set objWorkbook = objExcel.WorkBooks.Open("path of the file.xls")
Set objDriverSheet = objWorkbook.Worksheets("name of the sheet / Id of the sheet")
columncount = objDriverSheet.usedrange.columns.count
rowcount = objDriverSheet.usedrange.rows.count
for i = 1 to colunmcount
  columnname = objDriversheet.cells(i,1)
  if columnname = knowncolumnname then
    for j = 1 to rowcount
      fieldvalue = objdriversheet.cells(j,i)
    next
  end if
next

 3rd method: Reading Excel Data using ADODB Connection

Function GetContentFromDB (strFileName, strSQLStatement)
Dim objAdCon, objAdRs
Set objAdCon = CreateObject(“ADODB.Connection”)

objAdCon.Open “DRIVER={Microsoft Excel Driver (*.xls)};DBQ=”&strFileName & “;Readonly=True”
If Err <> 0 Then
      Reporter.ReportEvent micFail,”Create Connection”, “[Connection] Error has occured. Error : ” & Err
      Set obj_UDF_getRecordset = Nothing
   Exit Function
End If

Set objAdRs = CreateObject(“ADODB.Recordset”)
objAdRs.CursorLocation=3                        ‘ set the cursor to use adUseClient – disconnected recordset
objAdRs.Open strSQLStatement, objAdCon, 1, 3

MsgBox objAdRs.fields(4).name
While objAdRs.EOF=false
   For i=0 to objAdRs.Fields.count
      Msgbox objAdRs.fields(i)
   Next
   objAdRs.moveNext
Wend

If Err<>0 Then
      Reporter.ReportEvent micFail,”Open Recordset”, “Error has occured.Error Code : ” & Err
      Set obj_UDF_getRecordset = Nothing
     Exit Function
End If

Set objAdRs.ActiveConnection = Nothing

objAdCon.Close
Set objAdCon = Nothing

End Function

Set rsAddin = GetContentsFromDB(“C:\Documents and Settings\gramesh\Desktop\Login.xls”, “Select * from [Login$]“)


No comments:

Post a Comment