Helpex - Trao đổi & giúp đỡ Đăng nhập
2

Tôi đã điều chỉnh mã từ câu trả lời @ tim-schmelter cho câu hỏi chuyển đổi dữ liệu csv sang DataTable trong VB.net (xem bên dưới)

Tôi muốn phân tích cú pháp trong các tiêu đề cột từ hàng 0 của tệp csv

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

nhưng tôi không gặp may khi cố gắng tìm ra cách làm điều này. bất kỳ đề xuất sẽ rất được đánh giá cao.

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 hữu ích 0 bình luận 13k xem chia sẻ
7

Chỉ cần lặp qua tất cả các dòng của tệp. Sử dụng boolean để kiểm tra hàng đầu tiên.

Public Function csvToDatatable_2(ByVal filename As String, ByVal separator As String)
 Dim dt As New System.Data.DataTable
 Dim firstLine As Boolean = True
 If IO.File.Exists(filename) Then
   Using sr As New StreamReader(filename) 
     While Not sr.EndOfStream
       If firstLine Then
         firstLine = False
         Dim cols = sr.ReadLine.Split(separator)
         For Each col In cols 
           dt.Columns.Add(New DataColumn(col, GetType(String)))
         Next
       Else
         Dim data() As String = sr.Readline.Split(separator)
         dt.Rows.Add(data.ToArray)
       End If
      End While
   End Using
 End If
 Return dt
End Function
7 hữu ích 3 bình luận chia sẻ
0

Đây là sự kết hợp của hai giải pháp trên, với một số thay đổi khác:

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
0 hữu ích 0 bình luận chia sẻ
loading
Không tìm thấy câu trả lời bạn tìm kiếm? Duyệt qua các câu hỏi được gắn thẻ vb.net csv import datatable , hoặc hỏi câu hỏi của bạn.

Có thể bạn quan tâm

loading