首页 > 解决方案 > c# FileHelpers 将具有可变长度行的 csv 加载到 DataTable 中

问题描述

这篇接近回答我的问题的帖子之后,我需要一些帮助来设置 FileHelpers。我的银行对账单在实际交易数据上方有一些额外的信息,因此文件如下所示:

Some Header 1,Some Header 2,And Header 3
<summary of the entire file on 5 lines>

Date,Transaction Type,Description,Amount,Running Balance
<actual transaction data, on 5 columns each line>

我有兴趣捕获所有字段(在 DataTable 中),包括摘要。基本上,我希望根据任何行中的最大列数来调整数据表的大小。

Prasanth 提出了一个替代方案,但我不明白是什么_fileContent

using (MemoryStream stream = new MemoryStream(_fileContent)) //file content can be file as byte array

我已经用 VBA 编写代码多年,最近在 c# 中启动了一个 Excel Com-AddIn,所以我想我更像是一个新手。

先感谢您!丹妮

标签: c#csvfilehelpers

解决方案


FileHelpers MultiRecordEngine 可能会对此有所帮助,前提是您能够编写一个记录选择器,该记录选择器可以查看字符串记录并决定您要用于读取该行的格式。

通常,当您有一个明显的记录类型指示符时,这最有效 - 在这种情况下,该行的第一个字符表示记录类型:

 if (recordLine.Length == 0)
            return null;  // no record will be read

        int action = int.Parse(recordLine.Substring(0, 1));
        switch (action) {
            case 0:
            case 1:
                return typeof(RecTypeOne);
            case 2:
                return typeof(RecTypeTwo);
            case 3:
                return typeof(RecTypeThree);

            default:
                return null;  // again, no record is read

在您的情况下,您可能能够根据行中的逗号数做出此决定,这意味着字段数,但实际的确定性记录类型指示符会更可取,IMO。


推荐阅读