2013-08-17 125 views
0

我有一个具有以下结构的CSV文件:VB.NET只读一些细胞从CSV文件中的每一行

id,name,adress,email,age 
1,john,1 str xxxx,[email protected],19 
2,mike,2 bd xxxx,[email protected],21 
3,jeana,1 str ssss,[email protected],18 
....................... 
....................... 

我想什么做的是读取csv文件,跳过第一行(包含头文件)并从每行中提取第2,3和4个数据并填充datagridview。

这是我使用的代码,但是它带给我所有的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

这可能是简单的阅读的第一行,并丢弃它,然后开始从文件

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), "") 
+0

您好,感谢您的答复,关于阅读每一行这一目标数据是什么:第2,第3,第4? – OussamaLord

+0

对不起,我不明白。网格是否填充数据?你的意思是你想从网格中读取数据吗? – Steve

+0

嗨,是网格填充了来自csv的全部数据,但这不是我想要的,我希望它只填写来自csv文件中每行的“名称”,“地址”和“电子邮件”没有“ID”,也没有“年龄” – OussamaLord