我需要能够将电子表格中的列从'idn_prod‘重命名为’idn_prod1 1‘,但是有两个列具有这个名称。
我尝试过从类似的帖子中实现代码,但我只能更新这两列。在下面,您会发现我的代码只是重命名了两列。
//locate and edit column in csv
string file1 = @"C:\Users\username\Documents\AppDevProjects\import.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("idn_prod", "idn_prod1"));
}我希望只重命名第二列,但是实际的输出是这两个列都被重命名了。下面是CSV的前几行:

发布于 2019-10-29 22:00:29
我假设您只需要更新列标题,实际的行就不需要更新.
var file1 = @"test.csv";
var lines = System.IO.File.ReadAllLines(file1);
var columnHeaders = lines[0];
var textToReplace = "idn_prod";
var newText = "idn_prod1";
var indexToReplace = columnHeaders
.LastIndexOf("idn_prod");//LastIndex ensures that you pick the second idn_prod
columnHeaders = columnHeaders
.Remove(indexToReplace,textToReplace.Length)
.Insert(indexToReplace, newText);//I'm removing the second idn_prod and replacing it with the updated value.
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(file1))
{
sw.WriteLine(columnHeaders);
foreach (var str in lines.Skip(1))
{
sw.WriteLine(str);
}
sw.Flush();
}发布于 2019-10-29 21:36:19
将foreach(行中的字符串)循环替换为
对于循环,得到行数,并仅重命名第二列。
发布于 2019-10-29 21:48:34
我认为正确处理这一问题的唯一方法是将标题行(具有列名的第一个字符串)拆分为单独的部分,用逗号或制表符或其他什么分隔开,然后自己一次运行一列。
循环将考虑文件中的第一行,在分隔符上使用Split函数,并查找您感兴趣的列:
bool headerSeen = false;
foreach (string s in lines)
{
if (!headerSeen)
{
// special: this is the header
string [] parts = s.Split("\t");
for (int i = 0; i < parts.Length; i++)
{
if (parts[i] == "idn_prod")
{
// only fix the *first* one seen
parts[i] = "idn_prod1";
break;
}
}
sw.WriteLine( string.Join("\t", parts));
headerSeen = true;
}
else
{
sw.WriteLine( s );
}
}这甚至可能的唯一原因是它是标题而不是单独的行;标题在格式上更容易预测,并且您不太担心引用和包含分隔符的字段等等。
在单个数据行上尝试这一点很少能可靠地工作:如果分隔符是逗号,那么如果单个字段包含逗号,会发生什么情况?然后你必须担心引用,这就进入了各种各样的乐趣。
对于在C#中做任何真正的CSV工作来说,研究一个专门从事此功能的包是非常值得的,我对来自乔希Close的CsvHelper感到非常兴奋。强烈推荐。
https://stackoverflow.com/questions/58615657
复制相似问题