2017-02-17 121 views
0

我有很多不同的CSV文件与其中的数据(包括标题)。在csv文件中的位置编号2中添加列c#

我无法弄清楚如何在第二位添加新列。

我可以使用空值(每行)填充新单元格,但新列处于第一位置。

请参阅附件图片:新列必须位于IDINTA列之后。

enter image description here

任何人可以帮助我吗?

在此先感谢以下

我的代码。

output = System.Web.HttpContext.Current.Server.MapPath("/public/target.csv"); 

string[] CSVDump = File.ReadAllLines(output); 
List<List<string>> CSV = CSVDump.Select(x => x.Split('|').ToList()).ToList(); 
for (int i = 0; i < CSV.Count; i++) 
{ 
    CSV[i].Insert(0, i == 0 ? "Headername" : "Filename"); 
} 
File.WriteAllLines(output, CSV.Select(x => string.Join("|", x))); 

#Edit 01

enter image description here

#Edit 02

N|IDINTA|Filename|DDMMYYYY HHMMSS| 
+0

我能想到的方式是;将csv转换为DataTable。一旦数据在DataTable中存在,您可以在任何你想要的位置添加列。 – A3006

+0

那么你想插入哪一列?你能告诉我们它前后应该是什么样子吗? – wkl

+0

@wkl请参阅#在我的第一个问题中编辑02 –

回答

1

简单地改变指数在Insert声明:

CSV[i].Insert(2, i == 0 ? "Headername" : "Filename"); 

使用所希望的位置的变量,完整的代码如下:

// define the desired position here: 
int posNewColumn = 2; 

output = System.Web.HttpContext.Current.Server.MapPath("/public/target.csv"); 

string[] CSVDump = File.ReadAllLines(output); 
List<List<string>> CSV = CSVDump.Select(x => x.Split('|').ToList()).ToList(); 
for (int i = 0; i < CSV.Count; i++) 
{ 
    if(CSV[i].Count > posNewColumn) 
    { 
     CSV[i].Insert(posNewColumn , i == 0 ? "Headername" : "Filename"); 
    } 
    else 
    { 
    // append the new data at the end if the existing line is too short. 
    // You may want to do nothing instead or fill the appropriate number 
    // of empty cells before adding. 
     CSV[i].Add(i == 0 ? "Headername" : "Filename"); 
    } 
} 
File.WriteAllLines(output, CSV.Select(x => string.Join("|", x))); 
+0

谢谢你的帮助。请在我的第一个问题中查看**#编辑01 ** –

+0

@AntonioMailtraq如果您收到错误消息,指出索引必须在列表的范围内,那么我认为csv中有一行比其他行短。你应该检查一下。如果这是一项要求,请将其添加到问题中。 – wkl

+0

您的csv中可能有一行比其他行短,但编辑了数百行 –

0

这应该这样做。

output = System.Web.HttpContext.Current.Server.MapPath("/public/target.csv"); 

string[] CSVDump = File.ReadAllLines(output); 

var CSV = CSVDump.Select(x => x.Split('|').ToList()); 

var newInserted = CSV.Aggregate(new List<List<String>>(), (l, i) => 
{ 
    i.Insert(1, (l.Count == 0) ? "header" : "fileName"); 
    l.Add(i); 
    return l; 
}); 

File.WriteAllLines(output, newInserted.Select(x => string.Join("|", x))); 
+0

谢谢,但用您的代码不添加新列。 –

+0

lemme check,那么它不会出现在newInserted变量中? – kemiller2002

+0

括号错误) –