c# 文件帮助程序将具有可变长度行的 csv 加载到数据表中



在这篇接近回答我的问题的帖子之后,我需要一些帮助来设置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>

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

Prasanth提出了另一种选择,但我不明白_fileContent是什么:

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

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

提前谢谢你! 丹妮

使用 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());    
}

查看代码项目文章以获取更多帮助。

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

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。

最新更新