在datagrid视图vb.net中导入excel

我想在下面的代码中使用这个方法在datagridview中导入Excel。 但是我有一个错误在这行“invalidOperationException”不能得到数据显示

cnnExcel.Open() 

这里是整个代码

comboBox as cmbExcel有一些如果支持条件取决于Excel版本(2003 – 2013)

 Imports System.Data.OleDb Public Class Form1 Dim cnnExcel As New OleDbConnection Public Function GetExccelSheetNames() As String() Dim ConStr As String = "" Dim dt As DataTable = Nothing Dim opExcel As New OpenFileDialog opExcel.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls" opExcel.ShowDialog() Dim pathExcel As String = opExcel.FileName If pathExcel.Trim = "" Then MessageBox.Show("Please Select Excel File !") Return Nothing Else Dim Ext As String = pathExcel.Substring(pathExcel.LastIndexOf(".") + 1) If Ext.Length = 3 Then ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathExcel + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';" ElseIf Ext.Length = 4 Then ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathExcel + ";Extended Properties='Excel 12.0 xml;HDR=YES';" End If cnnExcel = New OleDbConnection(ConStr) cnnExcel.Open() dt = cnnExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) If dt Is Nothing Then Return Nothing End If Dim excelSheetNames As [String]() = New [String](dt.Rows.Count - 1) {} Dim i As Integer = 0 For Each row As DataRow In dt.Rows excelSheetNames(i) = row("TABLE_NAME").ToString() i += 1 Next cnnExcel.Close() Return excelSheetNames End If End Function 

添加一个button作为btnBrows从本地驱动器的任何位置浏览excel文件

 Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click cmbsheet.DataSource = GetExccelSheetNames() End Sub Dim dt As New DataTable 

然后最后有一个button来查看datagridview中的excel

 Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click Dim cmd As New OleDbCommand("Select * from [" + cmbsheet.SelectedValue.ToString() + "]", cnnExcel) cnnExcel.Open() dt.Clear() dt.Load(cmd.ExecuteReader()) cnnExcel.Close() DataGridView1.DataSource = dt End Sub 

末class

用这个作为参考。 这是100%的工作。 我在我的一个应用程序中使用这个。 把这个代码放在导入button上。

 Dim result As DialogResult = OpenFileDialog1.ShowDialog() Dim path As String = OpenFileDialog1.FileName Me.TextBox1.Text = path.ToString Try Me.dgvFile.DataSource = Nothing Dim MyConnection As System.Data.OleDb.OleDbConnection Dim MyCommand As System.Data.OleDb.OleDbDataAdapter MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Me.TextBox1.Text & "';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.DataTable MyCommand.Fill(DtSet) Me.dgvFile.DataSource = DtSet MyConnection.Close() MessageBox.Show("File successfully imported") Catch ex As Exception MessageBox.Show("Error") End Try