如何使用VB.NET使用CarriageReturn和LineFeed解析CSV文件?

sdnqo3pr  于 5个月前  发布在  .NET
关注(0)|答案(2)|浏览(53)

我需要分析一个CSV文件使用VB。NET使用CarriageReturn和LineFeed作为第三列包含逗号。CSV标题是ID,名称,说明。

Imports Microsoft.VisualBasic.FileIO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ID As String
        Dim Element As String
        Dim Description As String

        Dim tfp As New TextFieldParser("Z:\Downloads\test.csv")
        tfp.Delimiters = New String() {","}
        tfp.TextFieldType = FieldType.Delimited

        tfp.ReadLine() ' skip header
        While tfp.EndOfData = False
            Dim fields = tfp.ReadFields()
            ID = fields(0)
            Element = fields(1)
            Description = fields(2)

            CustomerBindingSource.DataSource = fields
        End While

    End Sub
End Class

字符串

35g0bw71

35g0bw711#

您可以使用Microsoft.VisualBasic.FileIO中的TextFieldParser类。该类有助于读取结构化文本文件,
参考以下代码以供参考:

Imports Microsoft.VisualBasic.FileIO
Imports System.IO

Module Module1
    Sub Main()
        Dim filePath As String = "path\to\your\file.csv"
        ParseCsvFile(filePath)
    End Sub

    Sub ParseCsvFile(filePath As String)
        Try
            Using parser As New TextFieldParser(filePath)
                parser.TextFieldType = FieldType.Delimited
                parser.SetDelimiters(",")

                ' Skip the header
                parser.ReadLine()

                While Not parser.EndOfData
                    Dim fields As String() = parser.ReadFields()

                    If fields.Length >= 3 Then
                        Dim id As String = fields(0)
                        Dim name As String = fields(1)
                        Dim description As String = fields(2)

                        ' Now you can use id, name, and description as needed
                        Console.WriteLine($"ID: {id}, Name: {name}, Description: {description}")
                    End If
                End While
            End Using
        Catch ex As Exception
            Console.WriteLine($"Error: {ex.Message}")
        End Try
    End Sub
End Module

字符串

5jdjgkvh

5jdjgkvh2#

考虑到第一行是一个header,并且ID和Element都不能包含逗号,您可以使用蛮力:

Dim DataLine As Boolean
  Dim FileSpec = "F:\temp\csvtest.txt"
  Dim lines = My.Computer.FileSystem.ReadAllText(FileSpec).Split(CChar(vbCr))
  For Each L In lines
     If DataLine Then     'skip header
        Dim a = L.Trim.Split(","c)
        Dim ID = a(0), Element = a(1), Description = a(2)
        For i = 3 To a.Length - 1
           Description &= "," & a(i)        'replace the missing comma
        Next
        'finally, do something with the values
        Dim t = ID & "/" & Element & "/" & Description
     Else
        DataLine = True
     End If
  Next

字符串

相关问题