像在標題中一樣,我解析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文件(見下圖),唯一的整數。
這究竟是爲什麼?
只需更改一行,即將空格上的行拆分爲分號:'string [] values = row.Split ';');' – itsme86
https://joshclose.github.io/CsvHelper/ – pm100
你是否在分割行 – pm100