我有 78 excel列,我有 5 datagridviews。
如何建立连接?
答案 0 :(得分:0)
我理解你想要达到的目标,但为了最大限度地解决问题,如果你添加一些代码或进一步解释会更好。 例如,如何知道哪些Excel数据应该在DataGridView中显示一个,等等......
无论如何,我建议您将任务分为两个步骤:
ReadExcel和DisplayData。在我看来,通过OLEDB从excel文件中读取数据是一个很好的开始。因此,我建议您阅读以下文章:http://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
要在DataGridView中显示数据,您需要将数据集绑定到它。也许你会发现以下帖子有用:
How to bind Dataset to DataGridView in windows application
它的两个c#代码,但我认为为vb.net运行是一件容易的事。
编辑:我发现了一些你可以使用的旧的vb.net。它不是那么好的代码,但它应该让你开始。它导入excel表的整个数据。但请不要只是复制并运行:)
Public Shared Function ImportExcelSheetData(ByVal ExcelFilePath As String, _
ByVal SourceExcelSheetName As String, _
ByRef pDestDataTable As DataTable, _
ByRef ErrMsg As String, _
Optional ByVal WithHeader As Boolean = False) As Integer
Dim ConnectionString As String = ""
Dim WithHeaderString As String = ""
Dim nOutputRow As Integer = 0
Dim oleExcelCommand As OleDbCommand
Dim oleExcelConnection As OleDbConnection
ImportExcelSheetData = -1 ' Error by default
If System.IO.File.Exists(ExcelFilePath) <> True Then
ErrMsg = "Error: File does not exist." + vbCrLf + "Filepath: " + ExcelFilePath
Exit Function
End If
If WithHeader = True Then
WithHeaderString = "Yes"
Else
WithHeaderString = "No"
End If
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=""Excel 12.0;HDR=" + WithHeaderString + ";IMEX=1"""
oleExcelConnection = New OleDbConnection(ConnectionString)
oleExcelConnection.Open()
If IsNothing(pDestDataTable) = True Then
pDestDataTable = New DataTable
End If
' if SourceExcelSheetName is not set, use first sheet!
If SourceExcelSheetName.Trim = "" Then
Dim tmpDataTable As DataTable = oleExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
if IsNothing(tmpDataTable) OR tmpDataTable.Rows.Count < 1 Then
throw new Exception("Error: Could not determine the name of the first worksheet.")
End If
Dim firstSheetName As String = tmpDataTable.Rows(0)("TABLE_NAME").ToString()
If firstSheetName.Trim() <> "" then
SourceExcelSheetName = firstSheetName
End If
End If
If SourceExcelSheetName <> "" Then
Try
Dim oleAdapter As New OleDbDataAdapter()
oleExcelCommand = oleExcelConnection.CreateCommand()
If SourceExcelSheetName.EndsWith ("$") = True Then
oleExcelCommand.CommandText = "Select * From [" & SourceExcelSheetName & "]"
Else
oleExcelCommand.CommandText = "Select * From [" & SourceExcelSheetName & "$]"
End If
oleExcelCommand.CommandType = CommandType.Text
oleAdapter.SelectCommand = oleExcelCommand
oleAdapter.Fill(pDestDataTable)
oleExcelConnection.Close()
Catch ex As Exception
ErrMsg = Err.Description
Exit Function
End Try
End If
ImportExcelSheetData = 0 ' Ok
结束功能