Imports excel = Microsoft.Office.Interop.Excel
Dim filePath As String
Private Sub btnExceltoGdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExceltoGdata.Click
Dim objOpenFileDialog As New OpenFileDialog
'Set the Save dialog properties
With objOpenFileDialog
.DefaultExt = "xls"
'.FileName = "Test"
.Filter = "Microsoft Excel (*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
'.OverwritePrompt = True
.Title = "Open File Excel"
End With
If objOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
'Open or Create the file
filePath = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, objOpenFileDialog.FileName)
DisplayExcel()
Catch fileException As Exception
Throw fileException
End Try
End If
'Clean up
objOpenFileDialog.Dispose()
objOpenFileDialog = Nothing
End Sub
Private Sub DisplayExcel()
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='" & filePath & "';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)
DataGridView.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
หมายเหตุ: อย่าลืม add references Microsoft excel 11.0 object library