[英]Parsing data from CSV file
就像標題一樣,我在解析CVS文件中的數據時遇到問題。 當我選擇具有不同格式的文件時,我得到的只是“輸入字符串的格式不正確”。 我的代碼適用於以下格式的文件:
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
這是負責從文件讀取數據並從中創建圖表的代碼:
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;
}
}
編輯
我將解析方法更改為此:
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文件中僅讀取整數(請參見下圖)。
為什么會這樣呢?
我建議您不要重新發明輪子,而是使用一些經過良好測試的庫來解析CSV(例如,您的實現不能很好地處理帶引號的值。它也不允許將分隔符作為值的一部分) 。
猜猜是什么:.NET包含可以幫助您的內容: TextFieldParser類。 不用擔心VisualBasic
命名空間-它也可以在C#中工作:-)
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()方法的返回類型為因此,如果布爾值返回true,則表示字符串轉換成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.