VB.NET: How to Display Excel Data on DataGridView

Again, about VB.NET and excel file. This time I want to display excel data on  datagridview. 

I use file that stored in D:\karyawan.xlsx, and here is what it looks like.


For the UI I only add a DataGridView named grdData into a form. 


Code behind:

Imports System.Data
Imports System.Data.OleDb

Public Class frmExcelGrid

    Private Sub frmExcelGrid_Load(
ByVal sender As System.Object, _
    ByVal 
As System.EventArgs) Handles MyBase.Load

        Dim exConn 
As OleDbConnection
        
Dim dt As DataSet
        
Dim cmd As OleDbDataAdapter

        
Dim sConn As String
        sConn = "provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & _
                "'d:\karyawan.xls';Extended Properties=Excel 8.0;"

        exConn = New System.Data.OleDb.OleDbConnection(sConn)
        cmd = New System.Data.OleDb.OleDbDataAdapter( _ 

              "select * from [Sheet1$]", exConn)
        cmd.TableMappings.Add("Table""Tabel Karyawan")
        dt = New System.Data.DataSet
        cmd.Fill(dt)
        grdData.DataSource = dt.Tables(0)
        exConn.Close()

    End Sub

End Class


We're using OleDbConnection with ConnectionString that stored in sConn variable. The sample code above is to used with excel file that has .xls extension or generated with Ms Excel 97-2003. Otherwise using .xlsx or Ms Excel 2007 or newer we can use:
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & _
        "'d:\karyawan.xlsx';Extended Properties=Excel 12.0;"


The excel 2007 keatas (.xlsx) could also read for 97-2003 (.xls), but sometimes the OLEDB version could be an issue. So fit connectionstring with version that you use.

Done with UI and code let's try to run.



Post a Comment

0 Comments