2013-10-24 23 views
0

我正在使用C#創建一個包含200個標題的CSV文件。我從另一個包含150個標題的CSV文件中獲取數據。我的問題是我將如何根據其標題放置數據。例如,我在下面給出例子。在C#中比較和創建CSV文件

將與C#創建的CSV文件:

Name, Surname, Locality, DateOfbirth, Age 
Joe, Smith,       60 
Sam, Brown,       20 

的CSV從

Name, Surname, Age 
Joe, Smith, 60 
Sam, Brown, 20 

獲取數據這是一個示例代碼(實際的文件包含150報頭,並且新的CSV文件包含200個標頭)

string[] lines = System.IO.File.ReadAllLines(fileUrl); 
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileUrl)) 
{ 
    foreach (string line in lines) 
    { 
     if (line == lines[0]) 
     { 
      //Changing the header of the first file 
      file.WriteLine("Name, Surname, Locality, DateOfBirth, Age"); 
     } 
     else 
     { 
      string[] values = line.Split(','); 
      file.WriteLine(string.Format("{0},{1},{2},{3},{4}", 
           values[0], values[1], values[2], values[3], values[4])); 
     } //exception being thrown here since the array is out of range 
    } 
} 
+0

你正在做'line.Split(',');'但我沒有看到任何逗號'實際的csv文件'? –

+0

我需要將原始文件中的數據保存到新文件中。 @DavidS。上述表格僅用於圖形目的,以便人們不會對數據產生困惑 – chrisd

+0

CSV文件的行在兩個文件中的順序是否相同?你一直都知道結構嗎? – AbstractChaos

回答

2

您正在讀取輸入文件中的三列,但正在試圖寫出五列。所以values[3]values[4]將超出範圍。

我很疑惑你在哪裏期待從LocationDateOfBirth得到。無論它在哪裏,它都不會在你的值數組中。

+0

我從另一個CSV文件中獲取 – chrisd

+0

@ChristianDebono第二個CSV文件是什麼?請在你的問題中包括這些細節。 –

0

從包含3列的文件中讀取數據。然後從另一個文件中讀取Locality和DateOfBirth值。清除第一個文件,然後將它們全部寫入新的csv文件。

public static List<string[]> Parse(string Path) 
    { 
     List<string[]> Parsed = new List<string[]>(); 

     using (StreamReader Reader = new StreamReader(Path)) 
     { 
      string Line; 
      char Seperator = ','; 

      while ((Line = Reader.ReadLine()) != null) 
      { 
       if (Line.Trim().StartsWith("//")) continue; 
       if (string.IsNullOrWhiteSpace(Line)) continue; 

       string[] Data = Line.Split(Seperator); 
       Parsed.Add(Data); 
      } 
     } 

     return Parsed; 
    } 

您可以使用上述方法從CSV文件讀取。想象一下,你閱讀第一個文件,你得到列表和字符串數組有3個值。

讀取第二個文件並獲取其他值。對於第一個列表中的每個值,在第二個列表中找到相應的項目。然後使用這兩個字符串數組列表來寫入一個csv文件。

List<string[]> File1 = Parse("File1Path"); 
List<string[]> File2 = Parse("File2Path"); 

using (System.IO.StreamWriter file = new System.IO.StreamWriter(OutputFile)) 
{ 
    // write header first:  
    file.WriteLine("Name, Surname, Locality, DateOfBirth, Age"); 

    foreach (string line in File1) 
    { 
    var found = File2.Where(x => x[0] == line[0]).FirstOrDefault();   
    if(null == found) continue; 

    file.WriteLine(string.Format("{0},{1},{2},{3},{4}", 
           line[0], line[1], found[3], found[4], line[2])); 
    } 
}