在vb.net中读取csv文件

时间:2014-11-07 00:05:16

标签: vb.net csv

我在vb.net中使用此代码来读取csv文件:

filename = TextBox1.Text
        FileOpen(1, filename, OpenMode.Input)

        'first row contains header information, therefore read it in, but ignore it
        dummy = LineInput(1)

        While Not EOF(1)

            Input(1, dialcode)
            Input(1, chargecode)
            Input(1, description)
            Input(1, mincharge)
            Input(1, onpeak)
            Input(1, offpeak)
            Input(1, weekendonpeak)
            Input(1, weekendoffpeak)
            Input(1, onpeakconnect)
            Input(1, offpeakconnect)
            Input(1, weekendonpeakconnect)
            Input(1, weekendoffpeakconnect)
End While

这项工作很好

但我现在有一个不同的CSV要读入,当我在记事本中打开CSV文件时,它在每一行的末尾有一个,所以它不读取每一行因为vb.net不确定何时一行端

1 个答案:

答案 0 :(得分:4)

.Net在TextFieldParser中有一个内置的CSV阅读器。它将为您处理额外的逗号或引用的分隔符等内容。例如,您可以这样做:

Dim dialcode As String
Dim chargecode As String
Dim mincharge As String

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


tfp.ReadLine() ' skip header
While tfp.EndOfData = False
    Dim fields = tfp.ReadFields()
    dialcode = fields(0)
    chargecode = fields(1)
    mincharge = fields(2)
    Console.WriteLine(String.Format("{0} - {1} - {2}", dialcode, chargecode, mincharge))
End While