当我不知道列名时使用 FileHelpers 解析 CSV 的示例

sample of parsing CSV w/ FileHelpers when I don't know column names

我正在尝试使用 FileHelper 3.1.5 来解析用户提供的 CSV 文件。我不知道编译时的列名。我需要一种动态读取列的方法,包括列数据和 header 信息。

是do-able吗?所有示例都解析为静态 类.

当然可以。使用 FileHelpers class builder 在运行时构建导入规范。类似于:

// create a FileHelpers class with a comma delimiter.
DelimitedClassBuilder cb = new DelimitedClassBuilder("Person", ",");
// add your fields based on whatever logic you like (e.g., maybe read the column names from the first row)
cb.AddField("firstName", typeof(string));
cb.AddField("lastName", typeof(string));
cb.LastField.FieldNullValue = "default last name";

// create your import engine from the class you created above.
DelimitedFileEngine engine = new DelimitedFileEngine(cb.CreateRecordClass());
DataTable dt = engine.ReadFileAsDT("data.csv");