【发布时间】:2015-08-11 11:16:39
【问题描述】:
我有 78 个 excel 列,我有 5 个数据网格视图。
如何建立连接?
【问题讨论】:
标签: excel datagridview vb.net-2010
我有 78 个 excel 列,我有 5 个数据网格视图。
如何建立连接?
【问题讨论】:
标签: excel datagridview vb.net-2010
我了解您想要实现的目标,但是为了最大限度地利用任何答案,最好添加一些代码或进一步解释。 例如,任何人都应该如何知道应该在 DataGridView 一、二等中显示哪些 excel 数据...
无论如何,我建议您将任务分为两个步骤:
读取 Excel 和 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
结束函数
【讨论】: