2014-11-24 112 views
0

我想解析CSV文件的數據沒有運氣,我已經嘗試了一大堆工具在線,沒有人能夠正確解析CSV文件。我感到困惑的是,我在這裏尋求幫助,因爲人們會認爲解析CSV數據會非常容易。解析CSV數據

CSV數據的格式是這樣的:

",95,54070,3635,""Test Reservation"",0,102,0.00,0.00,2014-12-31,""Name of customer"",""$12.34 + $10, special price"",""extra information"",,CustomerName,,,,,1234567890,[email protected],CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL," 

當前代碼:

private void btnOpenFileDialog_Click(object sender, EventArgs e) 
    { 
     DialogResult result = openFileDialog1.ShowDialog(); 

     if (result == DialogResult.OK) 
     { 
      using (StreamReader reader = new StreamReader(openFileDialog1.FileName)) 
      { 
       string line; 

       while ((line = reader.ReadLine()) != null) 
       { 
        ParseCsvLine(line); 
       } 
      } 
     } 
    } 

    private void ParseCsvLine(string line) 
    { 
     if (line != string.Empty) 
     { 
      string[] result; 

      using (var csvParser = new TextFieldParser(new StringReader(line))) 
      { 
       csvParser.Delimiters = new string[] { "," }; 

       result = csvParser.ReadFields(); 
      } 

      foreach (var item in result) 
      { 
       Console.WriteLine(item + Environment.NewLine); 
      } 
     } 
    } 

結果變量只有一個項目及其:

,95,54070,3635,"Test Reservation",0,102,0.00,0.00,2014-12-31,"Name of customer","$12.34 + $10, special price","extra information",,CustomerName,,,,,1234567890,[email protected],CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL, 
+0

通過編寫解析器或使用庫。 – CodeCaster 2014-11-24 11:14:51

+0

那麼,你的分隔符似乎是你的例子中的昏迷,你在分割命令中使用了一個選項卡。 – 2014-11-24 11:16:34

回答

0
// Add Microsoft.VisualBasic.dll to References. 
using Microsoft.VisualBasic.FileIO; 

// input is your original line from csv. 

// Remove starting and ending quotes. 
input = input.Remove(0, 1); 
input = input.Remove(input.Length - 1); 

// Replace double quotes with single quotes. 
input = input.Replace("\"\"", "\""); 

string[] result; 
using (var csvParser = new TextFieldParser(new StringReader(input))) 
{ 
    csvParser.Delimiters = new string[] { "," }; 
    result = csvParser.ReadFields(); 
} 
+0

Mihai有沒有其他建議? – user2595352 2014-11-24 13:10:06

+0

@ user2595352,是的,只是發佈我的編輯:)你必須刪除雙引號,並用單引號替換它們。另外,我已從行中刪除了開始和結束引號。這有點凌亂。也許有另一種解決方案。 – mihai 2014-11-24 13:11:24

+0

是的,似乎正確讀取它! :)我很困惑,爲什麼這似乎是一個如此複雜的任務,雖然,我的意思是我認爲CSV具有某種標準,它會很容易閱讀。感謝您的幫助! – user2595352 2014-11-24 13:20:49

0

您可以查看以前發佈的帖子與csv文件中的討厭逗號。我連接它here

Mihai,您的解決方案只適用於一條線路,但一旦有多條線路需要解析就會失敗。

+0

不,我不認爲它會失敗。只需將解決方案提取到一個函數中,該函數接受一個'string'並返回'string []'。另外,你的帖子不是答案。你應該使用這個評論。 – mihai 2014-11-24 11:45:20