vb.net – 如何读取CSV文件并在Visual Basic 2010中的网格中显示
发布时间:2020-12-17 00:10:12 所属栏目:大数据 来源:网络整理
导读:如何读取CSV文件并在Visual Basic 2010中的网格中显示结果?这听起来很简单,但是在谷歌搜索一段时间后,我仍然找不到答案.我在表单上有DataGridView,它被称为DataGridView1.我有一个csv只有3列的数据,我想要能够显示它们. 使用.Net框架内置的 TextFieldParser
如何读取CSV文件并在Visual Basic 2010中的网格中显示结果?这听起来很简单,但是在谷歌搜索一段时间后,我仍然找不到答案.我在表单上有DataGridView,它被称为DataGridView1.我有一个csv只有3列的数据,我想要能够显示它们.
使用.Net框架内置的
TextFieldParser类.
这是Paul Clement从MSDN forum post复制的一些代码.它将CSV转换为新的内存数据表,然后将DataGridView绑定到DataTable Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:Documents and Settings...My DocumentsMy DatabaseTextSemiColonDelimited.txt") TextFileReader.TextFieldType = FileIO.FieldType.Delimited TextFileReader.SetDelimiters(";") Dim TextFileTable As DataTable = Nothing Dim Column As DataColumn Dim Row As DataRow Dim UpperBound As Int32 Dim ColumnCount As Int32 Dim CurrentRow As String() While Not TextFileReader.EndOfData Try CurrentRow = TextFileReader.ReadFields() If Not CurrentRow Is Nothing Then ''# Check if DataTable has been created If TextFileTable Is Nothing Then TextFileTable = New DataTable("TextFileTable") ''# Get number of columns UpperBound = CurrentRow.GetUpperBound(0) ''# Create new DataTable For ColumnCount = 0 To UpperBound Column = New DataColumn() Column.DataType = System.Type.GetType("System.String") Column.ColumnName = "Column" & ColumnCount Column.Caption = "Column" & ColumnCount Column.ReadOnly = True Column.Unique = False TextFileTable.Columns.Add(Column) Next End If Row = TextFileTable.NewRow For ColumnCount = 0 To UpperBound Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString Next TextFileTable.Rows.Add(Row) End If Catch ex As _ Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & _ "is not valid and will be skipped.") End Try End While TextFileReader.Dispose() frmMain.DataGrid1.DataSource = TextFileTable (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |