【问题标题】:Is there a way to read a CSV file into an ArrayList and then print the values out on the console?有没有办法将 CSV 文件读入 ArrayList,然后在控制台上打印出来?
【发布时间】:2016-09-16 19:15:29
【问题描述】:

我只是在练习 C#。我主要习惯于 Java,但我一直无法弄清楚如何读取 .CSV 文件、存储它并将其内容打印到控制台中。这就是我到目前为止所拥有的。我做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = "C:\\Desktop\\csvTestFilePractice\\";
            String file1 = "testFile1.csv";
            ArrayList arryList1 = new ArrayList();
            String[] dataArray1;

            TextFieldParser CSVFile1 = new TextFieldParser(path + file1);
            CSVFile1.SetDelimiters(",");
            dataArray1 = CSVFile1.ReadFields();

            int count = 0;
            while (!CSVFile1.EndOfData)
            {
                dataArray1 = CSVFile1.ReadFields();
                Console.WriteLine(dataArray1);
            }
            Console.Read();
        }
    }
}

这也是我正在测试的文件。

______Excel 视图

ID  Name    Phone          State
1   Colt    864-367-8399    SC
2   Terry   864-367-8400    GA
3   Joe     864-367-8401    FL
4   Mark    864-367-8402    NC
5   Ashley  864-367-8403    CO

____记事本视图

ID,Name,Phone,State
1,Colt,864-367-8399,SC
2,Terry,864-367-8400,GA
3,Joe,864-367-8401,FL
4,Mark,864-367-8402,NC
5,Ashley,864-367-8403,CO

感谢您的建议

【问题讨论】:

  • 您有这一行:CSVFile1.SetDelimiters(","),但您的文件似乎没有用逗号分隔。
  • @ChrisDunaway 我很抱歉这是一个 CSV 文件,但我使用 excel 来提取数据。我将改为发布记事本数据
  • 你想怎么打印?除了WriteLine 语句之外,您发布的代码似乎还可以。您可以尝试Console.WriteLine(string.Join(",", dataArray1));,或者如果您需要以柱状格式打印,请尝试Console.WriteLine("{0,2} {1,-10} {2,-14} {3, -5}", dataArray1[0], dataArray1[1], dataArray1[2], dataArray1[3]);
  • @Andersnk 那篇文章没有回答我的具体问题。我有一个特定于我发布的代码的问题。

标签: c# csv arraylist


【解决方案1】:

无论如何,您都不应该使用 ArrayList,因为它是一种非泛型集合类型。您应该考虑如何将 CSV 解析为 List 以避免对您的对象进行装箱/拆箱。

【讨论】:

  • 那么我想用 ArrayLists 做的事情是不可能的吗?
  • 没有。但是 ArrayList 不应在新代码中使用。请改用List<T>List<T> 对应于 Java 中的 ArrayList<T>。在此处查看更多信息:stackoverflow.com/questions/391088/arraylist-vs-listobject
【解决方案2】:

根据 cmets 中的问题,这里是一个简短版本的程序,它使用每列的最大长度来创建格式字符串。它应该适用于几乎任何 csv 文件。我确信它可以改进。所有列都左对齐。

void Main()
{
    List<string[]> lines = new List<string[]>();

    TextFieldParser CSVFile1 = new TextFieldParser(@"g:\test\test.csv");
    CSVFile1.SetDelimiters(",");

    //Loop through the data and create a list.  Each entry in the list
    //is a string array.  This method may be impractical for very large 
    //files.
    while (!CSVFile1.EndOfData)
    {
        lines.Add(CSVFile1.ReadFields());
    }

    //Create a format string using the length of the longest string in each column
    string formatString = createFormatString(lines);

    //Loop through all the lines and write them to the console.
    foreach (var csvLine in lines)
    {
        Console.WriteLine(formatString, csvLine);
    }
}

//Create a format string based on the number of columns and the maximum
// size of each column
private string createFormatString(List<string[]> lines)
{
    var sb = new StringBuilder();

    //Use the first array to get the number of columns.  They should all be the same
    int numberOfColumns = lines[0].Length;

    //Loop through the number of columns and find the max length and append to the format string
    for (int i = 0; i < numberOfColumns; i++)
    {
        int maxColumnWidth = lines.Select(l => l[i].Length).Max();
        sb.AppendFormat("{{{0}, -{1}}}  ", i, maxColumnWidth);
    }

    return sb.ToString();
}

【讨论】:

  • 我收到string formatString = creatFormatString(lines); 的错误,它说非静态字段、方法或属性“Program.createFormatString(List)”需要对象引用
  • 我在 LinqPad 中对此进行了编码。如果您从常规 C# 控制台应用程序运行,请确保将 static 关键字添加到方法中:private static string createFormatString(...)
  • 这就是问题所在。感谢克里斯不仅发布答案,还坚持我原来的问题并在代码中使用 cmets 进行解释!
猜你喜欢
  • 2021-10-28
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多