VB.NET中的CSV到DataGrid

时间:2013-07-12 08:03:47

标签: vb.net

我不知道如何将我的CSV文件加载到vb2005的数据网格视图中。

我有以下两条记录

9,N,010324405,,,,,,,,05071958,UU,Yoeun,,,,,,,,,,,M,M,KHM,,P,RESID,,,,,"St. Lum,Phum Ti Pir,Chrouy Changva,Ruessei Kaev",,,,PP,,KHM,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,215,S,,DDD_70300098149,21082012,PLN,KHR,6000,1206013,N,N,6000,M,,12042013,67000.00,NO,120000,0,12052013,0,30042013,,,,

10,N,00032529,,,,,,,,18021962,SDM,Sok,,,,,,,,,,,M,M,KHM,,P,RESID,,,,,"#281,Phum Ti Muoy,Chrouy Changva,Ruessei Kaev",,,,PP,,KHM,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,215,S,,DDD_703004167,20022013,PLN,KHR,10000,1510013,N,N,12000,M,,1802013,15660.00,NO,75000,0,1505213,0,3002013,,,,

我的代码:

For Each line As String In System.IO.File.ReadAllLines(pathname)
        DataGridView1.Rows.Add(line.Split(","))
Next

我想读取这种格式加载到datagridview,任何解决方案?

3 个答案:

答案 0 :(得分:4)

尝试以下代码

Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(pathname)

TextFieldParser1.Delimiters = New String() {","}

While Not TextFieldParser1.EndOfData
    Dim Row1 As String() = TextFieldParser1.ReadFields()

    If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
        Dim i As Integer

        For i = 0 To Row1.Count - 1
            DataGridView1.Columns.Add("Column" & i + 1, "Column" & i + 1)
        Next
    End If

    DataGridView1.Rows.Add(Row1)
End While

答案 1 :(得分:0)

使用CSV库检查示例:

at Codeproject

答案 2 :(得分:0)

您可以使用OLEDBCommand关注此url,您可以阅读 CSV 格式。看看p.campbell的解决方案。