错误“从excel加载数据到datagridview时,无法创建字段[Sheet1 $]的子列表”

时间:2013-10-06 10:09:58

标签: vb.net excel datagridview import

我正在尝试用excel文件中的数据填充DataGridView(在本例中为grvExcelData)。但我收到以下错误:

  

“无法创建字段[Sheet1 $]的子列表”

下面是我的代码片段,我正在尝试填充数据网格视图。我也使用Visual Studio 2010进行编程

感谢您的提前帮助

Public Sub fillgrid()

    Dim conn1 As String
    conn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filenamepath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""

    Dim connection As OleDbConnection = New OleDbConnection(conn1)
    Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection)
    Dim ds As DataSet = New DataSet()

    Dim emptyfile As String = "The file does not have any records for inserting."
    Dim selectCmd As OleDbCommand = New OleDbCommand()
    selectCmd.Connection = connection

    selectCmd.CommandText = "SELECT * FROM [Sheet1$]"

    If connection.State = ConnectionState.Closed Then
        connection.Open()
    End If

    da.SelectCommand = selectCmd
    Dim dsCounter As Integer = da.Fill(ds, "[Sheet1$]")

    If dsCounter = 0 Then
        MessageBox.Show(emptyfile, "dsCounter")
    End If

    grvExcelData.DataSource = ds
    grvExcelData.DataMember = "Sheet1"
    grvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect

    da.Dispose()

    If connection.State = ConnectionState.Open Then
        connection.Close()
    connection.Dispose()
    End If

End Sub

1 个答案:

答案 0 :(得分:1)

更改

grvExcelData.DataMember = "Sheet1"

grvExcelData.DataMember = "[Sheet1$]"

enter image description here