使用fileHelpers库读取CSV中的列标题 [英] Read column headers in CSV using fileHelpers library

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

问题描述

我有一个CSV文件,其中的标题指示信息将在详细信息行中显示的顺序.一个例子是:

I have a CSV file where the headers indicate in which order the information is going to appear in the detail lines. An example would be:

COLUMN1,COLUMN2,COLUMN3
VALUE1,VALUE2,VALUE3

但也可以

COLUMN2,COLUMN3,COLUMN1
VALUE2,VALUE3,VALUE1

该类看起来像这样

public class CSVImportLineItem
{
    public string Column1 {get; set;}
    public string Column2 {get; set;}
    public string Column3 {get; set;}
}

有没有办法(使用 FileHelpers )读取标头,然后确定到属性的映射根据标题顺序?

Is there a way (using FileHelpers) to read the headers in and then determine the mapping to the properties based on the header order?

推荐答案

您可以使用 ClassBuilder助手类.

DelimitedClassBuilder cb = new DelimitedClassBuilder("LineItem");
// First field
cb.AddField("Column2", typeof(string));
// Second field
cb.AddField("Column1", typeof(string));
// Third field
cb.AddField("Column3", typeof(string));

engine = new FileHelperEngine(cb.CreateRecordClass());
LineItem[] lineItems = engine.ReadFile("FileIn.txt") as LineItem[];

您可以根据第一行的内容(您可以在FileHelpers之外阅读)更改字段的顺序.

You can change the order of the fields based on the contents of the first line (which you can read outside of FileHelpers).

另请参见,此处的答案.

这篇关于使用fileHelpers库读取CSV中的列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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