2017-01-09 85 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