C# 更新CSV文件C中的一列#
我想根据CSV文件中数据库的条件更新一列(第三列)。 对于CSV文件中部门为1500的员工,要删除100,并将其替换为 数据库表:C# 更新CSV文件C中的一列#,c#,asp.net,csv,C#,Asp.net,Csv,我想根据CSV文件中数据库的条件更新一列(第三列)。 对于CSV文件中部门为1500的员工,要删除100,并将其替换为 数据库表: EmpID DeptID 100 1500 101 1300 102 1500 CSV文件,如下所示: EmpID,EmpName,Score,Grade1,Grade2,Grade3 100,emp1,100,A1,A3 101,emp2,250,A1,A5,A2 102,emp3,100,A1 结果应该是这样的: 100,emp1,,A1,A3 101
EmpID DeptID
100 1500
101 1300
102 1500
CSV文件,如下所示:
EmpID,EmpName,Score,Grade1,Grade2,Grade3
100,emp1,100,A1,A3
101,emp2,250,A1,A5,A2
102,emp3,100,A1
结果应该是这样的:
100,emp1,,A1,A3
101,emp2,250,A1,A5,A2
102,emp3,,A1
首先,我无法替换第三列中的值,请参见下面的代码:
string file1 = @"F:\test.csv"; string[] lines = System.IO.File.ReadAllLines(file1);
System.IO.StreamWriter sw = new System.IO.StreamWriter(file1);
foreach(string s in lines) {
sw.WriteLine(s.Replace("100", ""));
}
sw.Close();
如果我在foreach循环中给出以下行:
sw.WriteLine(Regex.Replace(s, s.Split(',')[2], m => s.Split(',')[2].ToString().Replace("100", "")));
它将所有值从100替换为空字符串
您能告诉我如何替换第3列中的值吗
提前谢谢
var lines = new string[10];
var splitLines = lines.Select(l => l.Split(','));
foreach (var splitLine in splitLines)
{
if (splitLine[2] == "100")
{
splitLine[2] = "0";
}
var line = string.Join(",", splitLine);
// And then do what you wish with the line.
}