简体   繁体   English

解析CSV文件中的数据

[英]Parsing data from CSV file

Like in title I have problem with parsing data from CVS files. 就像标题一样,我在解析CVS文件中的数据时遇到问题。 When i choose file with diffrent formating all i get is "Input string was not in a correct format". 当我选择具有不同格式的文件时,我得到的只是“输入字符串的格式不正确”。 My code works with files formatted like that: 我的代码适用于以下格式的文件:

16.990750 4.0
17.000250 5.0
17.009750 1.0
17.019250 6.0

But cant handle files formatted like this one: 但是无法处理格式如下的文件:

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

This is code responsibile for reading data from file and creating chart from it: 这是负责从文件读取数据并从中创建图表的代码:

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;



            }
         }

EDIT 编辑

I changed parsing method to this one: 我将解析方法更改为此:

                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);
            }

It works okay but with one exception - It can't read decimals only integers from csv file(see the picture below). 它可以正常工作,但有一个例外-它不能从csv文件中仅读取整数(请参见下图)。

View of table in locals 表在当地人的看法

Why is this happening? 为什么会这样呢?

I suggest you don't re-invent the wheel, but use some well-tested library to parse the CSV (for example, your implementation does not handle quoted values well. It also doesn't allow the separator as part of a value). 我建议您不要重新发明轮子,而是使用一些经过良好测试的库来解析CSV(例如,您的实现不能很好地处理带引号的值。它也不允许将分隔符作为值的一部分) 。

And guess what: .NET includes something that could help you: the TextFieldParser class. 猜猜是什么:.NET包含可以帮助您的内容: TextFieldParser类。 Don't worry about the VisualBasic namespace - it works in C#, too :-) 不用担心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);
            }

In the second text format the separator is(;) and first row of the text has two strings therefore to convert a string to decimal use decimal.TryParse() instead of decimal.Parse().the return type of method TryParse() is boolean therefore if it returned true that means the string converted successful . 在第二种文本格式中,分隔符为(;),并且文本的第一行有两个字符串,因此将字符串转换为十进制请使用decimal.TryParse()而不是decimal.Parse()。TryParse()方法的返回类型为因此,如果布尔值返回true,则表示字符串转换成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM