如何打开CSV文件更新一些行,列,删除一些行并将其另存为VB.net中的另一个CSV文件?

时间:2011-08-25 20:03:00

标签: vb.net

我有一个csv文件。我需要打开它,根据列值删除整行,更新几列值并将文件保存为.dat文件。 我使用的是VB.net 2010

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ加载,删除和更新CSV,例如:

Const separator = ","c
Dim csvPath = "C:\Temp\USPresident.csv"
Dim datPath = "C:\Temp\USPresident.dat"
Dim rows = (From line In IO.File.ReadAllLines(csvPath)
               Select line.Split(separator)).ToList
' get all lines with specific value ' 
Dim presidentRows = (From cols In rows
               Where cols.Contains("William Howard Taft")).ToList
' remove these lines with Except'
Dim rowsWithoutPresident = rows.Except(presidentRows).ToList
' update some values '
For Each row In rowsWithoutPresident
    row(3) = "test-value"
Next
Dim newLines = (From cols In rowsWithoutPresident
               Select String.Join(separator, cols)).ToArray
IO.File.WriteAllLines(datPath, newLines)

使用this csv-file with US-presidents进行测试。

Option Strict On | Option Infer开| Option Explicit