使用C#将CSV文件读入数组 [英] Read a CSV file in to an array using C#

查看:106
本文介绍了使用C#将CSV文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将拉入,读取和分隔csv文件的代码.它有四列,没有标题.我一直在网上找几个小时,似乎没有人真正找到答案,所以我希望这里的人可以.读入后,由于它是设计的一部分,因此我需要能够将其拉得很特别.提前谢谢!

I am trying to create a code that will pull in, read, and separate a csv file. It has four columns with no titles. I've been searching for hours online and no one really seems to have the answer so I'm hoping that someone here can. After it is read in I need it to be able to be pulled very specifically as it is part of design. Thanks ahead of time!

推荐答案

您的问题有点含糊,但我会尽力回答.

Your question is a little vague, but I'll try and answer it as best I can.

(根据定义)CSV文件是包含逗号分隔值的文件-此处的关键是使用逗号作为定界符.就我个人而言,我发现在解析时使用其他定界符会减少不必要的麻烦.

A CSV file is (by definition) a file containing comma seperated values - the key here is that a comma is used as the delimiter. Personally, I find that using a different delimiter is prone to less nasties when parsing.

我创建了以下测试CSV文件:

I've created the following test CSV file:

Column1,Column2,Column3,Column4
Row1Value1,Row1Value2,Row1Value3,Row1Value4
Row2Value1,Row2Value2,Row2Value3,Row2Value4
Row3Value1,Row3Value2,Row3Value3,Row3Value4
Row4Value1,Row4Value2,Row4Value3,Row4Value4
Row5Value1,Row5Value2,Row5Value3,Row5Value4

这里有一些代码可以将该文件读入一些简单的结构中,然后您就可以对其进行操作了.您可能想通过为列和行(以及值)创建类来扩展此代码.

Here's some code to read that file into some simple structures that you can then manipulate. You might want to extend this code by creating classes for the columns and rows (and values as well).

        string sFileContents = "";

        using (StreamReader oStreamReader = new StreamReader(File.OpenRead("Test.csv")))
        {
            sFileContents = oStreamReader.ReadToEnd();
        }

        List<string[]> oCsvList = new List<string[]>();

        string[] sFileLines = sFileContents.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        foreach (string sFileLine in sFileLines)
        {
            oCsvList.Add(sFileLine.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
        }

        int iColumnNumber = 0;
        int iRowNumber = 0;

        Console.WriteLine("Column{0}, Row{1} = \"{2}\"", iColumnNumber, iRowNumber, oCsvList[iColumnNumber][iRowNumber]);

        iColumnNumber = 4;
        iRowNumber = 2;

        Console.WriteLine("Column{0}, Row{1} = \"{2}\"", iColumnNumber, iRowNumber, oCsvList[iColumnNumber][iRowNumber]);

请记住,值是由列号,然后是行号访问的.

Keep in mind that values are accessed by the column number, and then the row number.

我希望这会有所帮助.

这篇关于使用C#将CSV文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆