2017-01-09 47 views
0

像在标题中一样,我解析CVS文件中的数据时遇到了问题。当我选择不同格式的文件时,我所得到的只是“输入字符串格式不正确”。 我的代码工作与格式类似的文件:解析CSV文件中的数据

16.990750 4.0 
17.000250 5.0 
17.009750 1.0 
17.019250 6.0 

,但不能处理格式文件一样这一个:

Series1 - X;Series1 - Y; 
285.75;798 
285.79;764 
285.84;578 
285.88;690 

这是从文件中读取数据,并从中创造海图编responsibile:

if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      string cos = File.ReadAllText(openFileDialog1.FileName); 
      string[] rows = cos.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); 

      DataTable table = new DataTable(); 
      table.Columns.Add("xValue", typeof(decimal)); 
      table.Columns.Add("yValue", typeof(decimal)); 

      foreach (string row in rows) 
      { 
       string[] values = row.Split(' '); 
       DataRow ch = table.NewRow(); 
       ch[0] = Decimal.Parse(values[0], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); 
       ch[1] = Decimal.Parse(values[1], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); 
       table.Rows.Add(ch); 

      } 
      if (seria == false) 
      { 
       wykres.Series.Add("series"); 
       wykres.Series["series"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; 
       wykres.Series["series"].XValueMember = "xValue"; 
       wykres.Series["series"].YValueMembers = "yValue"; 
       wykres.DataSource = table; 
       wykres.DataBind(); 

       seria = true; 



      } 
     } 

编辑

我改变了解析会见HOD这一个:

   foreach (string row in rows) 
      { 
       var values = row.Split(';'); 
       var ch = table.NewRow(); 
       decimal num = 0; 
       if (decimal.TryParse(values[0], out num)) 
        ch[0] = num; 
       if (decimal.TryParse(values[1], out num)) 
        ch[1] = num; 
       table.Rows.Add(ch); 
      } 

它的工作不错,但有一个例外 - 它不能读取小数从csv文件(见下图),唯一的整数。

View of table in locals

这究竟是为什么?

+0

只需更改一行,即将空格上的行拆分为分号:'string [] values = row.Split ';');' – itsme86

+0

https://joshclose.github.io/CsvHelper/ – pm100

+0

你是否在分割行 – pm100

回答

1

我建议你不要重新发明轮子,而是使用一些经过良好测试的库来解析CSV(例如,你的实现不能很好地处理引用值,它也不允许分隔符作为部分的价值)。

并猜测:.NET包含的东西可以帮助您:TextFieldParser类。不要担心VisualBasic命名空间 - 它也可以在C#中运行:-)

0
foreach (string row in rows) 
      { 
       var values = row.Split(';'); 
       var ch = table.NewRow(); 
       decimal num = 0; 
       if (decimal.TryParse(values[0], out num)) 
        ch[0] = num; 
       if (decimal.TryParse(values[1], out num)) 
        ch[1] = num; 
       table.Rows.Add(ch); 
      } 

在第二个文本格式的分离器是(;)和文本的第一行具有两个字符串因此将字符串到十进制使用decimal.TryParse(转换),而不是decimal.Parse()的返回。 TryParse()方法的类型是boolean ,因此如果它返回true,表示字符串转换成功。

+1

在解决当前问题中添加一些解释并回答这个问题的答案OP在解决当前问题 –

+0

@CodeCaster我对此解决方案有问题。我不知道为什么,但每个整数都从文件正确解析,但小数被忽略。 [与当地人保持联系的形象](http://i.imgur.com/Hs99Iau.png)。 – eredin