我有一个小的csv文件,其中必须添加colomn标头。 一列包含当前日期,但也包含""这对我来说很难找到用C#删除。 例如 该文件包含
"22022016",18,39,29,84
必须是:
A B C D E
22-02-2016 18 39 29 84
我尝试了下面的代码,但是在??我必须填写一个值,但这已经在第二行了。 另一个问题是替换""需要我认为特殊的字符。
提前致谢
DirectoryInfo d12 = new DirectoryInfo(@"C:\proef");
FileInfo[] infos12 = d12.GetFiles();
foreach (FileInfo f12 in infos12)
{
// #1 Read CSV File
string[] CSVDump = File.ReadAllLines(f12.FullName);
// #2 Split Data
List<List<string>> CSV = CSVDump.Select(x =>
x.Split(',').ToList()).ToList();
//#3 Update Data
for (int i = 0; i < CSV.Count; i++)
{
CSV[i].Insert(0, i == 0 ? "<Date>" : "Needs a value but this in the secondrom"
CSV[i].Insert(1, i == 0 ? "A" : "");
CSV[i].Insert(2, i == 0 ? "B" : "");
}
//#4 Write CSV File
File.WriteAllLines(f12.FullName, CSV.Select(x => string.Join(",", x)));
答案 0 :(得分:1)
要在csv的开头插入一行,请更改:
//#3 Update Data
for (int i = 0; i < CSV.Count; i++)
{
CSV[i].Insert(0, i == 0 ? "<Date>" : "Needs a value but this in the secondrom"
CSV[i].Insert(1, i == 0 ? "A" : "");
CSV[i].Insert(2, i == 0 ? "B" : "");
}
要:
//#3 Update Data
CSV.Insert(0, new List<string>{"<Date>", "A", "B"}); // 0 is index of first row
修改行:
int rowID = 1; // Index of row to modify
if (rowID < CSV.Count)
{
CSV[rowID][0] = "new date";
CSV[rowID][1] = "new A";
CSV[rowID][2] = "new B"
}