非常简单的C#CSV阅读器

时间:2009-09-03 19:23:37

标签: c# csv

我想从CSV文件创建一个数组。

这很简单,你可以想象,CSV文件只有一行和这些值:

Device, SignalStrength, Location, Time, Age.

我想把这些值放到一维数组中。

我已经尝试了一些例子,但它们都比需要的更复杂。

6 个答案:

答案 0 :(得分:64)

你可以试试下面的LINQ片段。

string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");

    var query = from line in allLines
                let data = line.Split(',')
                select new
                {
                    Device = data[0],
                    SignalStrength = data[1],
                    Location = data[2], 
                    Time = data[3],
                    Age = Convert.ToInt16(data[4])
                };

更新:在一段时间内,事情发生了变化。截至目前,我更愿意使用此库http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx

答案 1 :(得分:51)

如果只有一行,那么就这样做:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        String[] values = File.ReadAllText(@"d:\test.csv").Split(',');
    }
}

答案 2 :(得分:8)

这是我做的一个简单的功能。它接受字符串CSV行并返回字段数组:

它适用于Excel生成的CSV文件以及许多其他变体。

    public static string[] ParseCsvRow(string r)
    {

        string[] c;
        string t;
        List<string> resp = new List<string>();
        bool cont = false;
        string cs = "";

        c = r.Split(new char[] { ',' }, StringSplitOptions.None);

        foreach (string y in c)
        {
            string x = y;


            if (cont)
            {
                // End of field
                if (x.EndsWith("\""))
                {
                    cs += "," + x.Substring(0, x.Length - 1);
                    resp.Add(cs);
                    cs = "";
                    cont = false;
                    continue;

                }
                else
                {
                    // Field still not ended
                    cs += "," + x;
                    continue;
                }
            }

            // Fully encapsulated with no comma within
            if (x.StartsWith("\"") && x.EndsWith("\""))
            {
                if ((x.EndsWith("\"\"") && !x.EndsWith("\"\"\"")) && x != "\"\"")
                {
                    cont = true;
                    cs = x;
                    continue;
                }

                resp.Add(x.Substring(1, x.Length - 2));
                continue;
            }

            // Start of encapsulation but comma has split it into at least next field
            if (x.StartsWith("\"") && !x.EndsWith("\""))
            {
                cont = true;
                cs += x.Substring(1);
                continue;
            }

            // Non encapsulated complete field
            resp.Add(x);

        }

        return resp.ToArray();

    }

答案 3 :(得分:4)

上面这个固定版本的代码记住了CVS行的最后一个元素; - )

(使用包含5400行和26行元素的CSV文件进行测试)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

答案 4 :(得分:3)

这是我在项目中使用的,解析单行数据。

    private string[] csvParser(string csv, char separator = ',')
    {
        List <string> = new <string>();
        string[] temp = csv.Split(separator);
        int counter = 0;
        string data = string.Empty;
        while (counter < temp.Length)
        {
            data = temp[counter].Trim();
            if (data.Trim().StartsWith("\""))
            {
                bool isLast = false;
                while (!isLast && counter < temp.Length)
                {
                    data += separator.ToString() + temp[counter + 1];
                    counter++;
                    isLast = (temp[counter].Trim().EndsWith("\""));
                }
            }
            parsed.Add(data);
            counter++;
        }

        return parsed.ToArray();

    }

http://zamirsblog.blogspot.com/2013/09/c-csv-parser-csvparser.html

答案 5 :(得分:0)

首先需要了解什么是CSV以及如何编写它。

(大多数答案(目前所有答案都没有)使用这些要求,这就是为什么它们都错了!)

  1. 下一个字符串(/r/n)是下一个字符串&#34; table&#34;行。
  2. &#34;表&#34;单元格由一些分隔符号分隔。
  3. 作为分隔符可以使用任何符号。通常这是\t,
  4. 每个单元格可能在单元格中包含此分隔符符号(单元格必须以双引号符号开头,并且在这种情况下最后有双引号)
  5. 每个单元格可能包含单元格内的/r/n个符号(单元格必须以双引号符号开头,并且在这种情况下最后有双引号)
  6. 前段时间我曾根据标准Microsoft.VisualBasic.FileIO库编写了简单的CSV读/写类。使用这个简单的类,您将能够像使用2维数组一样使用CSV。

    使用我的库的简单示例:

    Csv csv = new Csv("\t");//delimiter symbol
    
    csv.FileOpen("c:\\file1.csv");
    
    var row1Cell6Value = csv.Rows[0][5];
    
    csv.AddRow("asdf","asdffffff","5")
    
    csv.FileSave("c:\\file2.csv");
    

    您可以通过以下链接找到我的课程并调查其编写方式: https://github.com/ukushu/DataExporter

    这个库代码的工作速度非常快,源代码非常简短。

    PS:同时此解决方案无法统一。

    PS2:另一种解决方案是使用库&#34; LINQ-to-CSV&#34;。它也必须运作良好。但它会更大。

相关问题