在 vb.net 中读取 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26791786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:26:26  来源:igfitidea点击:

read csv file in vb.net

vb.netcsv

提问by user2710234

I use this code in vb.net for reading in csv files:

我在 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

this work fine

这工作很好

but i now have a different CSV to read in, and it has a , at the end of each line when i open the CSV file in notepad, so its not reading each row in because vb.net is unsure when a row ends

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

回答by John Koerner

.Net has a built in CSV reader in the TextFieldParser. It will handle things like extra commas or quoted delimiters for you. For example, you could do this:

.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