ReadStreamAsDT - Filehelpers 和 C# - 如何使用 filehelpers 动态读取 CSV?

发布于 2024-10-10 07:02:57 字数 152 浏览 3 评论 0原文

我正在尝试通过 FileHelpers 动态读取 CSV 并将 CSV 数据作为数据表使用。我的 CSV 文件不会相同。它们将具有不同的列标题和不同数量的列。我正在使用 ReadStreamAsDT 方法,但似乎仍然需要一个结构化类来初始化 FileHelperEngine。有什么想法吗?

I am attempting to read in a CSV dynamically via FileHelpers and work with the CSV data as a datatable. My CSV files will not be the same. They will have different column headers and different amounts of columns. I am using the ReadStreamAsDT method, but it seems to still want a structured class to initialize the FileHelperEngine. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

来日方长 2024-10-17 07:02:57

我必须使用 FileHelpers.RunTime 和 DelimitedClassBuilder 从文件创建一个 DataTable。这是我的方法。如果我有更多时间,我会更好地解释这一点。

private static DataTable CreateDataTableFromFile(byte[] importFile) {
    var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = "," };
    var ms = new MemoryStream(importFile); 
    var sr = new StreamReader(ms); 
    var headerArray = sr.ReadLine().Split(',');
    foreach (var header in headerArray) { 
        cb.AddField(header, typeof(string)); 
        cb.LastField.FieldQuoted = true; 
        cb.LastField.QuoteChar = '"'; 
    }
    var engine = new FileHelperEngine(cb.CreateRecordClass());
    return engine.ReadStreamAsDT(sr);
}

显然,围绕此方法进行了大量验证以及其他逻辑,但我现在没有太多时间深入研究它。希望这有帮助!

I had to use FileHelpers.RunTime and the DelimitedClassBuilder to create a DataTable from the file. Here is my method. If I get more time, I will explain this better.

private static DataTable CreateDataTableFromFile(byte[] importFile) {
    var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = "," };
    var ms = new MemoryStream(importFile); 
    var sr = new StreamReader(ms); 
    var headerArray = sr.ReadLine().Split(',');
    foreach (var header in headerArray) { 
        cb.AddField(header, typeof(string)); 
        cb.LastField.FieldQuoted = true; 
        cb.LastField.QuoteChar = '"'; 
    }
    var engine = new FileHelperEngine(cb.CreateRecordClass());
    return engine.ReadStreamAsDT(sr);
}

Obviously, there is a lot of validation along with other logic taking place around this method, but I do not have much time right now to dive into it. Hope this helps!

梦年海沫深 2024-10-17 07:02:57

您是否尝试过使用 http://www.codeproject.com/KB/database/CsvReader.aspx ?您可以利用该库的解析。它快速且可靠。

Have you tried using http://www.codeproject.com/KB/database/CsvReader.aspx ? You could leverage this library's parsing. It's fast and reliable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文