Retrieve records in an Excel Sheet with VB.NET and OLE DB (Object Linking and Embedding Database)

You can access an Excel file as a database and read (or update) the contents with VB.NET by using SQL statements or reading the whole file into a VB.NET DataSet for further processing.

1. Add two references to your .NET project:


2. Define some variables in your VB.NET method:

Dim myguixt = New guixt
Dim MyConnection As OleDb.OleDbConnection
Dim DtSet As DataSet
Dim MyCommand As OleDb.OleDbDataAdapter
Dim sqlcondition As String
Dim excelfile As String = "d:\Excel\SampleData.xls"

3. Check if the file can be accessed:


 File.Open(excelfile, FileMode.Open, FileAccess.Write, _

 Catch ex As IOException
 MsgBox("File could not be opened/accessed")

End Try

When the file is open in Excel, it cannot be accessed by the OLE DB interface!

4. Open a connection to the Excel file via OLE DB:

MyConnection = New OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & excelfile _ 
& "';Extended Properties=Excel 8.0")

6. Mapping to a DataSet:

In order to read the data in VB.NET we need a mapping to a DataTable:

MyCommand.TableMappings.Add("Table", "DataTable1")

Then you can read in the data from the Excel file into a new DataSet:

DtSet = New DataSet

In this case you can access the columns e.g. by index number. We recommend using a mapping to an existing DataSet (called DataSet1 in this example):  

You should also set the DataType to System.Object so the OLE DB interface is not trying to guess the data type.

DtSet = New DataSet1

Now we can close the connection:


7. Finally you can access the data in the DataSet:

For Each r As DataRow In DtSet.Tables(0).Rows
  countRows += 1
  ' Read a value
  Dim total = ""
  total = r.Item("Total").ToString

  ' Add row to SAP table
  myguixt.SetVariable("table_regions.cell.col_total." _ 
   & countRows.ToString, total)

Catch ex As Exception

End Try

' Read row and add it to our View
DataGridView5.Rows.Add({r.Item(1), r.Item(6)})
' or

Next r
Components InputAssistant+Controls