将csv数据转换为VB.net中的DataTable,从第0行捕获列名

时间:2015-05-12 21:17:41

标签: vb.net csv import datatable

我已经修改了@ tim-schmelter对问题convert csv data to DataTable in VB.net的回答(见下文)

我想解析csv文件第0行的列标题

DT|Meter Number|Customer Account Number|Serial Number|Port...

但是我没有运气试图弄清楚如何做到这一点。任何建议都将非常感激。

Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String)
    '////////////////////////////////////////
    'Reads a selected txt or csv file into a datatable 
    'based on code from  http://stackoverflow.com/questions/11118678/convert-csv-data-to-datatable-in-vb-net
    '////////////////////////////////////////
    Dim dt As System.Data.DataTable

    Try
        dt = New System.Data.DataTable
        Dim lines = IO.File.ReadAllLines(filename)
        Dim colCount = lines.First.Split(separator).Length

        For i As Int32 = 1 To colCount
            dt.Columns.Add(New DataColumn("Column_" & i, GetType(String)))
        Next

        For Each line In lines
            Dim objFields = From field In line.Split(separator)
            Dim newRow = dt.Rows.Add()
            newRow.ItemArray = objFields.ToArray()
        Next

    Catch ex As Exception
        Main.Msg2User(ex.Message.ToString)
        Return Nothing

    End Try

    Return dt

End Function

2 个答案:

答案 0 :(得分:5)

只需循环遍历文件的所有行。使用布尔值检查第一行。

A 23
A 45
A 32
A 61
A 78
B 23
B 45
B 32
B 61
B 78
C 23
**C 32
C 45**
C 61
C 78

答案 1 :(得分:0)

以上是上述两种解决方案的混合体,还有一些其他变化:

Public Shared Function FileToTable(ByVal fileName As String, ByVal separator As String, isFirstRowHeader As Boolean) As DataTable
  Dim result As DataTable = Nothing
  Try
    If Not System.IO.File.Exists(fileName) Then Throw New ArgumentException("fileName", String.Format("The file does not exist : {0}", fileName))
    Dim dt As New System.Data.DataTable
    Dim isFirstLine As Boolean = True
    Using sr As New System.IO.StreamReader(fileName)
      While Not sr.EndOfStream
        Dim data() As String = sr.ReadLine.Split(separator, StringSplitOptions.None)
        If isFirstLine Then
          If isFirstRowHeader Then
            For Each columnName As String In data
              dt.Columns.Add(New DataColumn(columnName, GetType(String)))
            Next
            isFirstLine = True ' Signal that this row is NOT to be considered as data.
          Else
            For i As Integer = 1 To data.Length
              dt.Columns.Add(New DataColumn(String.Format("Column_{0}", i), GetType(String)))
            Next
            isFirstLine = False ' Signal that this row IS to be considered as data.
          End If
        End If
        If Not isFirstLine Then
          dt.Rows.Add(data.ToArray)
        End If
        isFirstLine = False ' All subsequent lines shall be considered as data.
      End While
    End Using
  Catch ex As Exception
    Throw New Exception(String.Format("{0}.CSVToDatatable Error", GetType(Table).FullName), ex)
  End Try
  Return result
End Function