【问题标题】:c# FileHelpers load into DataTable a csv with variable length linesc# FileHelpers 将具有可变长度行的 csv 加载到 DataTable 中
【发布时间】:2018-10-13 21:24:23
【问题描述】:

在接近回答我的问题的this post 之后,我需要一些帮助来设置 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# csv filehelpers


    【解决方案1】:

    使用Cinchoo ETL - 一个开源库,您可以加载可变长度的 CSV 文件。下面的示例显示了如何

    string csv = @"Id, Name, City
        1, Tom, NY
        2, Mark, NJ, 100
        3, Lou, FL
        4, Smith, PA
        5, Raj, DC";
    
    StringBuilder sb = new StringBuilder();
    using (var p = ChoCSVReader.LoadText(csv)
        .WithFirstLineHeader(true) //Ignore the header line to handle the variable length CSV lines
        .Configure(c => c.MaxScanRows = 5) //Set the max scan rows to the highest to figure out the max fields
        .Configure(c => c.ThrowAndStopOnMissingField = false)
        )
    {
        foreach (var rec in p)
            Console.WriteLine(rec.DumpAsJson());    
    }
    

    查看 CodeProject 文章以获得更多帮助。

    免责声明:我是这个库的作者。

    【讨论】:

      【解决方案2】:

      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 最好使用实际的确定性记录类型指示符。

      【讨论】:

        猜你喜欢
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 2015-08-09
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多