从许多

时间:2017-10-25 12:46:52

标签: c# asp.net asp.net-mvc file csv

我有一个基本上看起来像这样的CSV文件:

TransactionID         ProfileID       Date           // more columns here...
somevalue             123123123      somedate
somevalue             123123123      somedate              
somevalue             123123123      somedate
somevalue             123123123      somedate
somevalue             123123123      somedate

我想从CSV文件中仅提取所有这些列中的ProfileID和Date的特定列,方法是将其映射到现有类,如下所示:

public class MyMappedCSVFile
{
  public string ProfileID { get; set; } 
  public string Date { get; set; }
}

或者将其存储在字典集合中?

我尝试过这样的事情:

   public static List<string> ReadInCSV(string absolutePath)
        {
            List<string> result = new List<string>();
            string value;
            using (TextReader fileReader = File.OpenText(absolutePath))
            {
                var csv = new CsvReader(fileReader);
                csv.Configuration.HasHeaderRecord = false;
                while (csv.Read())
                {
                    for (int i = 0; csv.TryGetField<string>(i, out value); i++)
                    {
                        result.Add(value);
                    }
                }
            }
            return result;
        }

但是这会从CSV文件中取出所有内容,实际上是单个列表中的所有内容,而这不是我想要的......

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:4)

此代码中仍然要跳过标题,但使用此代码,您可以选择要提取的列。如果您使用StreamReader,可能会快得多。 并且您将需要一个构造函数用于您的对象。

var temp = File.ReadAllLines(@"C:\myFile.csv");
public List<MyMappedCSVFile>() myExtraction = new List<MyMappedCSVFile>();
foreach(string line in temp)
{
  var delimitedLine = line.Split('\t'); //set ur separator, in this case tab

  myExtraction.Add(new MyMappedCSVFile(delimitedLine[0], delimitedLine[3]));
}

对象代码:

public class MyMappedCSVFile
{
  public string ProfileID { get; set; } 
  public string Date { get; set; }

  public MyMappedCSVFile(string profile, string date)
  {
    ProfileID = profile;
    Date = date;
  }
}

答案 1 :(得分:0)

CvsHelper是一个很好的软件包,可以用于此类事情,它可以让你通过索引或名称获取。

文件中的一个例子是

t b

文档提供了大量读取文件并对其进行迭代,映射到类等的示例。看起来很完美。

https://github.com/JoshClose/CsvHelper

这是一个更完整的解决方案,以帮助您解决阅读问题(因为您已经安装了软件包)

// Don't forget to read the data before getting it.
csv.Read();

// By position
var field = csv[0];

// By header name
var field = csv["HeaderName"];

记录将是映射到您对象的CSV行列表。

答案 2 :(得分:0)

您好您可以根据需要使用此代码段来阅读任何类型的csv文件,只需很少的自定义。

public class CsvRow : List<string>
{
    public string LineText { get; set; }
}


public class CsvFileReader : StreamReader
{
    public CsvFileReader(Stream stream)
        : base(stream)
    {
    }

    public CsvFileReader(string filename)
        : base(filename)
    {
    }

    public bool ReadRow(CsvRow row,char separator)
    {
        try
        {
            row.LineText = ReadLine();
            if (String.IsNullOrEmpty(row.LineText))
                return false;

            int pos = 0;
            int rows = 0;

            while (pos < row.LineText.Length)
            {
                string value;

                // Special handling for quoted field
                if (row.LineText[pos] == '"')
                {
                    // Skip initial quote
                    pos++;

                    // Parse quoted value
                    int start = pos;
                    while (pos < row.LineText.Length)
                    {
                        // Test for quote character
                        if (row.LineText[pos] == '"')
                        {
                            // Found one
                            pos++;

                            // If two quotes together, keep one
                            // Otherwise, indicates end of value
                            if (pos >= row.LineText.Length || row.LineText[pos] != '"')
                            {
                                pos--;
                                break;
                            }
                        }
                        pos++;
                    }
                    value = row.LineText.Substring(start, pos - start);
                    value = value.Replace("\"\"", "\"");
                }
                else
                {
                    // Parse unquoted value
                    int start = pos;
                    while (pos < row.LineText.Length && row.LineText[pos] != separator)
                        pos++;
                    value = row.LineText.Substring(start, pos - start);
                }

                // Add field to list
                if (rows < row.Count)
                    row[rows] = value;
                else
                    row.Add(value);
                rows++;

                // Eat up to and including next comma
                while (pos < row.LineText.Length && row.LineText[pos] != separator)
                    pos++;
                if (pos < row.LineText.Length)
                    pos++;
            }
            // Delete any unused items
            while (row.Count > rows)
                row.RemoveAt(rows);

            // Return true if any columns read
            return (row.Count > 0);
        }
        catch (Exception ex)
        {
            ex.ToString();
            throw;
        }
    }
}  
  

比调用函数如下

using (CsvFileReader reader = new CsvFileReader(filePath))
            {
                char separator = ';'; //CSV file separated by (in this case it is semicolon)
                List<MyMappedCSVFile> lst=new List<MyMappedCSVFile>();
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row,separator))
                {  
                    if (row[0].Equals("TransactionID")) //to skip header
                        continue;
                    else
                    {
                       MyMappedCSVFile obj=new MyMappedCSVFile();
                       obj.ProfileID =row[1]; //Column Index of ProfileID
                       obj.Date = row[2]; // Column index of Date 
                       lst.Add(obj);
                    }
                }
            }  

filePath是csv文件的路径