读取csv文件c#

发布于 2024-09-14 16:17:39 字数 48 浏览 4 评论 0原文

有没有办法将 csv 文件读入矩阵,这样文件中的每个方块都将是矩阵中的一个单元格?

is there any way to read a csv file into a matrix, so every square in the file will be a cell in the matrix?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暮光沉寂 2024-09-21 16:17:39

有许多开源 CSV 阅读器,而且编写自己的代码也很容易。

首先请查看 codeplex.com:
http://kbcsv.codeplex.com/

或 Codeproject 教程:
http://www.codeproject.com/KB/database/CsvReader.aspx

为了完整起见,这里是我自己的实用程序类,用于从 CSV 文件中读取一行:

    /// <summary>
    /// Defines CSV reader states
    /// </summary>
    enum State
    {
        Initial, 
        Quote,
        Data,
        NestedQuote
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="CsvReader"/> class.
    /// </summary>
    /// <param name="inputStream">The input stream.</param>
    public CsvReader(Stream inputStream)
    {
        if (inputStream == null) 
            throw new ArgumentNullException("inputStream");

        reader = new StreamReader(inputStream);
    }

    /// <summary>
    /// Reads a single line of CSV data.
    /// </summary>
    /// <returns>Array of CSV fields</returns>
    public string[] Read()
    {
        var line = reader.ReadLine();
        var retval = new List<string>();

        if (line == null) 
            return null;

        var state = State.Initial;
        var text = new StringBuilder();

        foreach (var ch in line)
            switch (state)
            {
                case State.Initial:
                    if (ch == '"') 
                        state = State.Quote;
                    else if (ch == ',') 
                        retval.Add(string.Empty);
                    else
                    {
                        text.Append(ch);
                        state = State.Data;
                    }

                    break;

                case State.Data:
                    if (ch == ',')
                    {
                        retval.Add(text.ToString());
                        text.Length = 0;
                        state = State.Initial;
                    }
                    else 
                        text.Append(ch);

                    break;

                case State.Quote:
                    if (ch == '"')
                        state = State.NestedQuote;
                    else 
                        text.Append(ch);

                    break;

                case State.NestedQuote:
                    if (ch == '"')
                    {
                        text.Append('"');
                        state = State.Quote;
                        break;
                    }

                    state = State.Data;
                    goto case State.Data;
            }

        retval.Add(text.ToString());

        return retval.ToArray();
    }

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
        reader.Dispose();
    }

制作矩阵(未经测试):

var data = new List<string[]>();
string[] line;

using(reader = new CsvReader(stream))
  while((line = reader.Read()) != null)
    data.Add(line);

result = data.Select(row => row.Select(cell => int.Parse(cell)).ToArray()).ToArray();

There are many open source CSV readers, and it's also easy to code your own.

For a start take look at codeplex.com:
http://kbcsv.codeplex.com/

Or Codeproject tutorials:
http://www.codeproject.com/KB/database/CsvReader.aspx

For sake of completion, here is my own utility class to read a line from a CSV file:

    /// <summary>
    /// Defines CSV reader states
    /// </summary>
    enum State
    {
        Initial, 
        Quote,
        Data,
        NestedQuote
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="CsvReader"/> class.
    /// </summary>
    /// <param name="inputStream">The input stream.</param>
    public CsvReader(Stream inputStream)
    {
        if (inputStream == null) 
            throw new ArgumentNullException("inputStream");

        reader = new StreamReader(inputStream);
    }

    /// <summary>
    /// Reads a single line of CSV data.
    /// </summary>
    /// <returns>Array of CSV fields</returns>
    public string[] Read()
    {
        var line = reader.ReadLine();
        var retval = new List<string>();

        if (line == null) 
            return null;

        var state = State.Initial;
        var text = new StringBuilder();

        foreach (var ch in line)
            switch (state)
            {
                case State.Initial:
                    if (ch == '"') 
                        state = State.Quote;
                    else if (ch == ',') 
                        retval.Add(string.Empty);
                    else
                    {
                        text.Append(ch);
                        state = State.Data;
                    }

                    break;

                case State.Data:
                    if (ch == ',')
                    {
                        retval.Add(text.ToString());
                        text.Length = 0;
                        state = State.Initial;
                    }
                    else 
                        text.Append(ch);

                    break;

                case State.Quote:
                    if (ch == '"')
                        state = State.NestedQuote;
                    else 
                        text.Append(ch);

                    break;

                case State.NestedQuote:
                    if (ch == '"')
                    {
                        text.Append('"');
                        state = State.Quote;
                        break;
                    }

                    state = State.Data;
                    goto case State.Data;
            }

        retval.Add(text.ToString());

        return retval.ToArray();
    }

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
        reader.Dispose();
    }

To make the matrix (untested):

var data = new List<string[]>();
string[] line;

using(reader = new CsvReader(stream))
  while((line = reader.Read()) != null)
    data.Add(line);

result = data.Select(row => row.Select(cell => int.Parse(cell)).ToArray()).ToArray();
无言温柔 2024-09-21 16:17:39

VisualBasic 命名空间中有一个文本阅读器,可以在 C# 中使用,并且可以很好地处理可怕的 CSV 文件:

TextFieldParser

只需在项目中添加对 Microsoft.VisualBasic 的引用即可。

There is a text reader in the VisualBasic namespace that can be used in C# and handles even horrible CSV files very well:

TextFieldParser

Just add a reference to Microsoft.VisualBasic in your project.

夏九 2024-09-21 16:17:39

使用正则表达式解析 CSV: http://www.hotblue.com/article0000.aspx? a=0006

要使用自定义分隔符扩展概念,请参阅这篇文章:如何我是否需要编写一个正则表达式来匹配不包含单词的字符串?

CSV parsing with regular expressions: http://www.hotblue.com/article0000.aspx?a=0006

To expand the concept with custom separators, see this post: How do I write a regex to match a string that doesn't contain a word?

歌枕肩 2024-09-21 16:17:39

有很多方法。从逐字节读取器开始。这取决于您的 csv 文件格式(带/不带标题、行结尾、" 或 ')。我已经编写了自己的类。

一个很好的阅读器:

http://www.stellman-greene.com/CSVReader/

There are many ways. Starting with a byte by byte reader. It depends on your csv file format (with/without header, line endings, " or '). I've written my own class.

A good reader to start with:

http://www.stellman-greene.com/CSVReader/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文