Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Imports System
Imports System.Windows.Forms
Public Class Form1
Private Excel03ConString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"
Private Excel07ConString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RadioButton1.Checked = True
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String = Path.GetExtension(filePath)
Dim header As String = If(RadioButton1.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
End Select
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
End Class