像在标题中一样,我解析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