Ecco
codice:
Public Sub caricaExcell()
Dim DS As New DataSet
'Dim numRighe As Integer
'Dim indRiga As Integer
Dim strPerc As String
Try
'Apertura finestra di dialogo per apertura file
Dim apriFile As New OpenFileDialog
apriFile.InitialDirectory = App_Path()
apriFile.Multiselect = True
If apriFile.ShowDialog = DialogResult.OK Then
'apre excel
Dim excellApp = New Excel.Application
'Rende visibile Excel
'excellApp.Visible = False
'apre il file xls
strPerc = apriFile.FileName
'Gestire multiselezione
'Dim nFilesel = apriFile.FileNames
'Dim nFile As Integer
'nFile=asa.
Dim exWb = excellApp.Workbooks.Open(strPerc)
'seleziona il foglio di lavoro 1 del file excel
Dim numSheet = excellApp.Worksheets.Count
'Dim a = excellApp.Worksheets.Select(1)
Dim exWs = exWb.Worksheets(1)
Dim nameWs = exWs.name
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPerc & ";" & "Extended Properties=Excel 8.0")
con.Open()
Dim queryExcell As String = ("SELECT * FROM " & "[" & nameWs & "$]")
Dim cmd As New OleDb.OleDbDataAdapter(queryExcell, con)
DS = New DataSet
cmd.Fill(DS, "tabella")
DataGridViewExcell.DataSource = DS
DataGridViewExcell.DataMember = "Tabella"
exWb.Close()
excellApp.Quit()
con.Close()
'excellApp.Workbooks.Close()
caricaDatiDB()
End If
Catch ex As COMException
MessageBox.Show("Error accessing Excel: " + ex.ToString())
Catch ex As Exception
MessageBox.Show("Error: " + ex.ToString())
End Try
End Sub