CSV的新列/行数据

时间:2017-12-08 08:28:00

标签: vb.net csv

我有一个CSV文件,我需要添加新列app_modulnameapp_module.statusapp_module.incrementapp_module.success。这可以通过以下代码行轻松完成。

Dim csvData = File.ReadLines(filename).Select(Function(line, index) 
  If(index = 0, 
    line + ",app_module.name,app_module.status,app_module.increment,app_module.success",
    line + "," + moduleName & ",inactive," & index & ",")
  )

File.WriteAllLines(savePath, csvData)

对于app_module.increment列,行数据只是增量数字。问题是上面的代码正在读取换行符。并且,我使用index作为增量数。有没有其他方法来获取行的索引?

1 个答案:

答案 0 :(得分:0)

我开始使用以下文本文件:

One,"First record",Primary
Two,"Second
record",Secondary
Three,"Third record",Tertiary

我执行了这段代码:

Dim lines As New List(Of String)
Dim lineNumber = 1

Using parser As New TextFieldParser("TextFile1.txt") With {.Delimiters = {","}}
    Do Until parser.EndOfData
        Dim fields = parser.ReadFields()

        'Add quotes around the column that may be multiline.
        fields(1) = $"""{fields(1)}"""

        lines.Add(String.Join(",", fields) & "," & lineNumber)
        lineNumber += 1
    Loop
End Using

File.WriteAllLines("TextFile1.txt", lines)

我最终得到了这个文本文件:

One,"First record",Primary,1
Two,"Second
record",Secondary,2
Three,"Third record",Tertiary,3