VB.NET只读取csv文件中每行的一些单元格

时间:2013-08-17 13:46:34

标签: vb.net csv datagridview

我有一个csv文件,其结构如下:

id,name,adress,email,age
1,john,1 str xxxx,john@gmail.com,19
2,mike,2 bd xxxx,mike@gmail.com,21
3,jeana,1 str ssss,jeana@gmail.com,18
.......................
.......................

我想要做的是阅读csv文件,跳过第一行(包含标题)并从每行中提取第2,第3和第4个数据并填充数据网格视图。

这是我正在使用的代码,但它带给我所有的csv内容:

DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "ID"
DataGridView1.Columns(1).Name = "NAME"
DataGridView1.Columns(2).Name = "ADRESS"
DataGridView1.Columns(3).Name = "AGE"
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
            (openFile.FileName)//the csv path

                'Specify that reading from a comma-delimited file'
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(",")
                Dim currentRow As String()
                While Not MyReader.EndOfData
                    Try
           currentRow = MyReader.ReadFields()
           With DataGridView1.Rows.Add(currentRow) 'Add new row to data gridview'
                        End With
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
                    End Try
                End While
            End Using

那么有人可以告诉我该怎么做吗? 感谢。

1 个答案:

答案 0 :(得分:1)

读取第一行并丢弃它可能很简单,然后开始从文件中读取实际数据

Using MyReader As New TextFieldParser(openFile.FileName)
   MyReader.TextFieldType = FileIO.FieldType.Delimited
   MyReader.SetDelimiters(",")
   Dim currentRow As String()
   ' Read the first line and do nothing with it
   If Not MyReader.EndOfData Then
       currentRow = MyReader.ReadFields()
   End If
   While Not MyReader.EndOfData
      Try
          ' Read again the file
          currentRow = MyReader.ReadFields()
          DataGridView1.Rows.Add(currentRow(1), currentRow(2),currentRow(3)) 
      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
          MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
      End Try
  End While
End Using

编辑看到下面的评论然后我更改了添加行的行,只添加位置1,2和3的字符串。这当然不同于添加到DataGridView的列。目前尚不清楚是否要将这些列更改为仅包含这3个字段。如果您仍然希望网格中的ID和AGE列可以更改添加到

DataGridView1.Rows.Add("", currentRow(1), currentRow(2),currentRow(3), "")