使用datagridview从excel导入数据到datagridview在vb.net中已经有列

时间:2018-06-26 03:11:37

标签: excel vb.net datagridview

所以我想将数据从excel导入到datagridview。 Datagridview已经有列,当我尝试导入时,excel中的数据未排在datagridview的列中,而是将在右侧创建新列。该如何解决?

代码如下:

Dim conn As OleDbConnection
Dim dta As OleDbDataAdapter
Dim dts As DataSet
Dim excel As String
Dim OpenFileDialog As New OpenFileDialog

     Try
        OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        OpenFileDialog.Filter = "XLS files (*.xls, *.xlt)|*.xls;*.xlt|XLSX files (*.xlsx, *.xlsm, *.xltx, *.xltm)|*.xlsx;*.xlsm;*.xltx;*.xltm"
        If OpenFileDialog.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Dim fi As New IO.FileInfo(OpenFileDialog.FileName)
            Dim filename As String = OpenFileDialog.FileName
            excel = fi.FullName
            conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & excel & ";Extended Properties=Excel 12.0;")
            dta = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn)
            dts = New DataSet
            dta.Fill(dts, "[Sheet1$]")
            DataGridView1.DataSource = dts
            DataGridView1.DataMember = "[Sheet1$]"
            conn.Close()

        End If

    Catch ex As Exception
        MsgBox(ex.Message)
        conn.Close()
    End Try

1 个答案:

答案 0 :(得分:0)

只需在您的代码中编写此行,然后首先添加少量列即可测试此代码:

 DataGridView1.AutoGenerateColumns = True

此语句不会影响datagridview的现有列,也不会向datagridview添加新列。