2017-02-17 5 views
0

データが入っている(ヘッダを含む)CSVファイルがたくさんあります。csvファイルのcで位置番号2の列を追加してください。

位置番号2に新しい列を追加する方法を理解できません。

新しいセルをヌル値(各行)で塗りつぶすことはできますが、新しい列は最初の位置にあります。

添付画像をご覧ください:新しい列は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私の最初の質問で#Edit 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 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

それから、それはnewInserted変数に表示されていませんか? – kemiller2002

+0

カッコエラー) –

関連する問題