如何在运行时检测带有标题的CSV文件时检测列数据类型 [英] How to detect Column datatype at runtime, while parsing a CSV file with header

查看:126
本文介绍了如何在运行时检测带有标题的CSV文件时检测列数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FileHelpers 加载CSV数据,(贷方-在搜索找到的

I am using FileHelpers to load CSV data, (credit - while searching found this answer/search result).

用户浏览目录,选择带有标题的文件,然后上载以进行解析.我的问题是-它们是一个时间文件,其 cols/classes/types以前是未知的.

The user browses a dir., selects the files with headers, and uploads for parsing. My issues is that -- they are one time files, whose cols/classes/types are not known previously.

问题:解析时如何我检测到列的数据类型?

搜索后,我发现了一个名为public Type的函数 RecordType { get; }它提供了记录类型..我需要帮助来获取记录中的Col数据类型.

After searching I found a function called public Type RecordType { get; } it provides the record type.. I need help to get the Col data type in the record.

var fNengine = new FileHelperEngine<AttendeeEventManifesto>();
var fNrecords = engine.ReadFile("AttendeesByEvents.csv"); 

// How to get the Col types?
// HeaderText = typeof(..*notKNown*).GetCsvHeader();
//..var headers = fNrecords.HeaderText();

//foreach (var header in headers)
  //  Console.WriteLine(header.RecordType() + `\n`);     


我也在 SO 上找到了这个答案,但是@ shmap00提到的运行时帮助程序或他所指的帮助不再存在,我也查看了源代码树.能否有人将我指向链接


I also found this answer on SO, but the runtime helpers mentioned by @shmap00 or the help he is referring to is no longer there, i looked in the source tree as well. Can some one point me to the link please

推荐答案

您可以使用类构建器,可以在运行时像这样构建类:

You can use a class builder to build your class at runtime like this:

DelimitedClassBuilder cb = new DelimitedClassBuilder("MyProduct", delimiter: ",");

cb.AddField("Name", typeof(string));
cb.LastField.TrimMode = TrimMode.Both;

cb.AddField("Description", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.LastField.QuoteMode = QuoteMode.OptionalForBoth;

// etc... e.g., add a date field
cb.AddField("SomeDate", typeof(DateTime));

engine = new FileHelperEngine(cb.CreateRecordClass());

DataTable dt = engine.ReadFileAsDT("test.txt");

这篇关于如何在运行时检测带有标题的CSV文件时检测列数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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