-3

I have written the code below to read data from an Excel sheet and display data in a combobox in Visual Basic.

However, when I click "run" nothing is displayed.

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim MyConnection As New OleDb.OleDbConnection
        Dim MyCommand As New OleDb.OleDbCommand
        Dim filePath, sql As String
        filePath = "C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx"
        sql = "Select continent from [Sheet1]"
        MyConnection.ConnectionString = $"Provider= Microsoft.Jet._OLEDB 11.0;data source = {filePath};Extended_Properties=Excel 8.0"
        MyConnection.Open()
        MyCommand.Connection = MyConnection
        MyCommand.CommandText = sql
        Dim da As New OleDb.OleDbDataAdapter
        da.SelectCommand = MyCommand
        Dim dt As New DataTable
        da.Fill(dt)
        Me.ComboBox1.DataSource = dt
        Me.ComboBox1.DisplayMember = dt.Columns(0).ToString


        MyConnection.Close()
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
nesreen
  • 33
  • 1
  • 6
  • I’m not sure about most of the code here, but I’m pretty sure you need to separate filepath in the connection string. Terminate the string before it with a double quote, use the ampersand, then filepath. Reverse it on the back side. – wallyeye Jan 27 '19 at 17:32
  • @wallyeye See [Interpolated Strings (Visual Basic Reference)](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/interpolated-strings). – Andrew Morton Jan 27 '19 at 20:51

4 Answers4

1

Try this code

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim fname As String = "C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx"
        Dim connectionStringTemplate As String = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties=""Excel 12.0;HDR=Yes"""
        Dim connectionString As String = String.Format(connectionStringTemplate, fname)
        Dim sqlSelect As String = "SELECT * FROM [Sheet1$];"
        Dim workbook As DataSet = New DataSet()
        Dim excelAdapter As System.Data.Common.DataAdapter = New System.Data.OleDb.OleDbDataAdapter(sqlSelect, connectionString)
        excelAdapter.Fill(workbook)
        Dim worksheet As DataTable = workbook.Tables(0)
        ComboBox1.DataSource = worksheet
        Me.ComboBox1.DisplayMember = worksheet.Columns(0).ToString
    End Sub
patel
  • 430
  • 1
  • 4
  • 9
  • System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.' – nesreen Jan 27 '19 at 18:36
  • I tested the code on my machine, You can use Dim connectionStringTemplate As String = Provider=Microsoft.Jet._OLEDB 11.0;" + "Data Source={0};" + "Extended Properties=""Excel 8.0;HDR=Yes""" – patel Jan 27 '19 at 18:44
1

To read an xlsx file, rather than an xls file, you will need the ACE provider instead of the JET provider. You need to add the Extended Property "HDR=Yes" to tell it there is a header row.

The name of a worksheet needs a $ after it.

To make up a connection string, you can use a connectionstringbuilder - it will take care of adding any quotes or whatever is needed to create a valid connection string from the individual parts.

A DataAdapter will open and close the connection for you.

Some entities use unmanaged resources (i.e. they don't get automatically cleaned up after use) - they will have a .Dispose() method which will release those resources. Or you can use the Using construct to have it taken care of for you.

I used the ColumnName property instead of ToString as it is more obvious what it is.

I made a small Excel xlsx file to test with and used this program:

Imports System.Data.OleDb

Public Class Form1

    Sub PopulateCB()
        Dim filepath = "C:\temp\Continents.xlsx"

        Dim csb As New OleDbConnectionStringBuilder
        csb.Provider = "Microsoft.ACE.OLEDB.12.0"
        csb.DataSource = filepath
        csb.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES")

        Dim sql = "SELECT Continent FROM [Sheet1$]"
        Dim dt As New DataTable

        Using da As New OleDbDataAdapter(sql, csb.ConnectionString)
            da.Fill(dt)
        End Using

        ComboBox1.DataSource = dt
        ComboBox1.DisplayMember = dt.Columns(0).ColumnName

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        PopulateCB()

    End Sub

End Class

to get a combobox like this:

enter image description here

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
0

First thing to check before going into code, compatibility between your database and your excel . If you are using a 32bits excel version you will never be able to query a 64bits database.

Philippe Merle
  • 115
  • 2
  • 4
  • 13
  • thanks I managed to solve the problem , but I have written this sql statement ________ dt = GetDatafromExcelsheet("C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx", "select country from [Sheet1$] where continent = '" & ComboBox1.SelectedValue & "' ") – nesreen Jan 28 '19 at 19:58
  • and I got this error message _____ System.InvalidCastException HResult=0x80004002 Message=Operator '&' is not defined for string "select country from [Sheet1$] wh" and type 'DataRowView'. – nesreen Jan 28 '19 at 20:03
0

Start with something simple, and then work up to more complex things.

Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet

        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Open("c:\test1.xlsx")
        xlWorkSheet = xlWorkBook.Worksheets("sheet1")
        'display the cells value B2
        MsgBox(xlWorkSheet.Cells(2, 2).value)
        'edit the cell with new value
        xlWorkSheet.Cells(2, 2) = "http://vb.net-informations.com"
        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

    End Sub

    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

End Class

Make this work, and then add in a ComboBox object.

http://vb.net-informations.com/excel-2007/vb.net_excel_2007_open_file.htm

ASH
  • 20,759
  • 19
  • 87
  • 200