Monday, October 7, 2013

Importing data to Data grid from Excel worksheet in VB.net


Step 1
Create a vb form as shown below with the following controls.
A button control, a file open dialogue box


Type the code in the General
Imports System.Data.SqlClient

Type the code in the button click event.
Dim myStream As String
        OpenFileDialog1.Title = "Please Select a .Xls format File"
        OpenFileDialog1.InitialDirectory = "c:\"
        OpenFileDialog1.Filter = "Excel Worksheets|*.xls"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True

        If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Try
                myStream = OpenFileDialog1.FileName.ToString
                If (myStream IsNot Nothing) Then
                    ' Insert code to read the stream here.
                    Dim MyConnection As System.Data.OleDb.OleDbConnection
                    Dim DtSet As System.Data.DataSet
                    Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
                    MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myStream & ";Extended Properties=Excel 8.0;")
                    MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
                    MyCommand.TableMappings.Add("Table", "Net-informations.com")
                    DtSet = New System.Data.DataSet
                    MyCommand.Fill(DtSet)
                    DataGridView1.DataSource = DtSet.Tables(0)
                    MyConnection.Close()
                End If

            Catch Ex As Exception
                MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
            Finally
                ' Check this again, since we need to make sure we didn't throw an exception on open.
                If (myStream IsNot Nothing) Then
                End If
            End Try
        End If
    End Sub

No comments:

Post a Comment