仅读取CSV文件中的特定列

仅读取CSV文件中的特定列

本文介绍了仅读取CSV文件中的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a CSV file which looks like this basically:

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

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

I would like to extract only specific columns which are ProfileID and Date out of all these columns from the CSV file, either by mapping it to an existing class like this:

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

还是通过将其存储在Dictionary集合中?

Or by storing it in a Dictionary collection?

我尝试过这样的事情:

   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文件中删除所有内容,实际上是将所有内容都放在一个列表中,这不是我想要的...

But this takes out everything out of the CSV file, literally everything in a single List, and it's not what I want...

有人可以帮我吗?

推荐答案

此代码中的标题仍要跳过,但是使用此代码,您可以选择要提取的列.如果使用StreamReader,可能会更快.并且您将需要为对象创建一个构造器.

The header is still to skip in this code, but with this code, you can choose which columns to extract. It might be much faster if you use a StreamReader.And you will need a constructor for your object.

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;
  }
}

这篇关于仅读取CSV文件中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:56