2017-12-06 7 views
1

私は、CSVファイルを持っている:トランスポーズCSV(C#)は

enter image description here私はフォーマットの下にそれを変換する必要があり

enter image description here

は、私はこれだけをやりました

StreamReader srd = new StreamReader(path: path); 
    int rowCount = 0; 

    string[] oStreamDataValues = null; 
    string[] headerNames = null; 

    while (!srd.EndOfStream) 
    { 
     string oStreamRowData = srd.ReadLine().Trim(); 
     oStreamDataValues = oStreamRowData.Split(';'); 

     //headers 
     if (rowCount == 0) 
     { 
      headerNames = oStreamDataValues; 
      rowCount++;//second row go to "else"      
     } 
     //create new csv 
     else 
     { 

     }    
     //rowCount++; 
    } 
    //Console.WriteLine("number of lines " + rowCount); 
    srd.Dispose(); 

新しい形式に転記してもらえますか? t?

  else 
      { 
       string leftColumn = oStreamDataValues[0]; 

       for (int i = 1; i < oStreamDataValues.Length; i++) 
       { 
        string middleColumn = headerNames[i]; 
        string rightColumn = oStreamDataValues[i]; 
        string newRow = string.Join(";", leftColumn, middleColumn, rightColumn, Environment.NewLine); 

        File.AppendAllText(pathToNewFile, newRow); 
       } 
      } 

EDIT:

答えて

1

あなたはあなたのためのelse節を、これを試すことができますか使用LINQの:

var result = headerNames.Skip(1).Zip(oStreamDataValues.Skip(1), (a, b) => String.Join(";", oStreamDataValues[0], a, b));

+0

OK、しかしパスとして、私は新しいCSVファイルされるべきだと思いますか? (あなたのコードの最後の行) – 4est

+0

@ 4est正解!その行は少し "擬似コード"でした。私は自分の反応を編集しました。 – torsan

+0

がチェックされていて、動作しています........ LINQで行うことは可能でしょうか? – 4est

0
using System; 
using System.IO; 

namespace SharpTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string path = "XXX/test.csv"; 
      string savePath = "XXX/test2.txt";   
      using(StreamReader sr = new StreamReader(path)) 
      { 
       string headerLine = sr.ReadLine(); 
       string[] headers = headerLine.Split(';'); 
       using(StreamWriter sw = new StreamWriter(savePath)) 
       { 
        while (true) 
        { 
         string line = sr.ReadLine(); 
         if (line == null) return; 
         string[] ss = line.Split(';'); 
         if (ss.Length != headers.Length) continue; 
         for (int i = 1; i < headers.Length; i++) 
         { 
          sw.WriteLine(ss[0] + ";" + headers[i] + ";" + ss[i]); 
         } 
        } 
       } 
      } 
     } 
    } 
} 

テストCSV:

ID、Col2に; Col3; Col4
DEF;ID1; 10 20
のId2; 30; AAA; 40

+0

私はコードをテストしましたが、CSVは空です – 4est

+0

は私のtest.csvファイル@ 4est – skyoxZ

+0

でもそれが間違っているが、@トルーザンの答えは素晴らしい仕事です – 4est