如何在 c# 中使用列名而不是列号仅检索 csv 的几个列数据

  • 本文关键字:csv 检索 数据 几个 c# c#-4.0
  • 更新时间 :
  • 英文 :


我有一个由许多列组成的csv。从该csv中,我只需要选择几个必需的列。

我写的代码是

for (int i = 0; i < lineCount; i++)
{
var line = str.ReadLine();
if (line != null)
{
var values = line.Split(',');
dataInformation.Add(new DataInformation
{
timestamp_iso = values[3],
last_attributed_touch_data_tilde_campaign = values[9],
last_attributed_touch_data_tilde_channel = values[11],
last_attributed_touch_data_tilde_feature = values[12],
last_attributed_touch_data_tilde_ad_set_name = values[19],
user_data_platform = values[69],
user_data_aaid = values[70],
user_data_idfa = values[71],
user_data_idfv = values[72]
});
}
} 

我在使用它时得到错误的值。是否有任何其他方法可以使用列名而不是列号来检索值。

数据信息是一个类

public class DataInformation
{
public string timestamp_iso { get; set; }
public string last_attributed_touch_data_tilde_campaign { get; set; }
public string last_attributed_touch_data_tilde_channel { get; set; }
public string last_attributed_touch_data_tilde_feature { get; set; }
public string last_attributed_touch_data_tilde_ad_set_name { get; set; }
public string user_data_platform { get; set; }
public string user_data_aaid { get; set; }
public string user_data_idfa { get; set; }
public string user_data_idfv { get; set; }
}

请帮我解决这个问题。

我建议使用库来处理CSV格式。CsvHelper是一个很好的。它允许按列名访问字段:

csv.Read();
var field = csv["HeaderName"];

CSV 格式可能看起来很简单,但有一些极端情况(如引号(,因此最好使用现有解决方案。

我使用以下代码来获取 DataInformation 类型的所有记录。

using (TextReader fileReader = File.OpenText(FileName))
{
var csv = new CsvReader(fileReader);
dataInformation = csv.GetRecords<DataInformation>().ToList();
}

之后,我使用以下代码来获取所需的列。

using (TextWriter writer = new StreamWriter(ConfigurationManager.AppSettings["downloadFilePath"] + ConfigurationManager.AppSettings["fileName"] + date + ConfigurationManager.AppSettings["csvExtension"].ToString()))
{
using (var csv = new CsvWriter(TextWriter.Synchronized(writer)))
{
csv.WriteHeader(typeof(DataInformation));
csv.NextRecord();
csv.WriteRecords(dataInformation);
}
}

它对我有用。

最新更新