2014-11-24 105 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