我正在使用以下代码将Excel工作表导入到datagridview。如果Datagridview中没有预定义的列,那没有问题,但是当我导入文件时,我有预定义的列,它会创建新的列。如何防止这种情况。
Public Shared Sub NewMethod2(ByVal dgv As DataGridView)
Dim filepath As String
Dim ofd As OpenFileDialog = New OpenFileDialog With {
.Filter = "Excel Files | *.xlsx",
.Title = "Import Model Info Sheet"
}
Try
If ofd.ShowDialog() = DialogResult.OK Then
filepath = Path.GetFullPath(ofd.FileName)
Globals.ModelInfoSheet = filepath
End If
frmMain.Label1.Text = Globals.ModelInfoSheet
dgv.DataSource = Nothing
Dim MyConnection As OleDb.OleDbConnection
Dim MyCommand As OleDb.OleDbDataAdapter
MyConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Globals.ModelInfoSheet & "';Extended Properties=Excel 12.0;")
MyCommand = New OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("srcTablePa", "setTablePa")
Dim DtSet As DataTable
DtSet = New DataTable
MyCommand.Fill(DtSet)
dgv.DataSource = DtSet
MyConnection.Close()
MessageBox.Show("File successfully imported")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
答案 0 :(得分:-2)
您可以尝试一下吗(在Try ... Catch之间)?
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';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.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
End Class