FileHelpers 在字段中引用和逗号
Posted
技术标签:
【中文标题】FileHelpers 在字段中引用和逗号【英文标题】:FileHelpers quote and comma in fields 【发布时间】:2017-03-23 11:24:02 【问题描述】:我有一个使用 FileHelpers 解析的 csv 文件,但我遇到了一个字段中同时出现引号和逗号的情况:
逗号:
323,"PC","28/02/2014","UNI001","5000",0,"Return","Returned Goods, damaged",88.00,15.40,"T1","N",0.00,"R","-",
引用
148,"SI","13/01/2014","CGS001","4000",1,"5","17" Monitor",266.00,45.39,"T1","Y",311.39,"R","-",
我的班级是:
[DelimitedRecord(",")]
public class Transaction
public int TRAN_NUMBER;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string TypeText;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string DATE;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string TransactionAccount;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string NOMINAL_CODE;
public int DEPT_NUMBER;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string INV_REF;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string DETAILS;
public string NET_AMOUNT;
public string TAX_AMOUNT;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string TaxCodeName;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string PAID_FLAG;
public string AMOUNT_PAID;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string VatReconText;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string BankReconText;
public string RECON_DATE;
我找到了这个帖子 FileHelpers nested quotes and commas - parsing error
engine.BeforeReadRecord += (sender, args) =>
args.RecordLine = args.RecordLine.Replace(@"""", "'");
但它只有助于引号出现问题,而不是逗号。
这两个问题都可以通过 FileHelpers 解决还是我应该寻找替代解决方案?
【问题讨论】:
我自己解决这个问题的方法是解析成行,然后如果行不满足所需的字段数,+下面的行等等。 【参考方案1】:您可以实施BeforeReadRecord
事件来“修复”您的坏行。
FileHelperEngine engine = new FileHelperEngine<Transaction>();
engine.BeforeReadRecord += BeforeEvent;
private void BeforeEvent(EngineBase engine, BeforeReadRecordEventArgs e)
var line = e.RecordLine;
// you have to write the following replacement routine...
var fixedLine = ReplaceEmbeddedCommasAndQuotesWithSomethingDifferent(line);
e.RecordLine = fixedLine; // replace the line with the fixed version
并且在您阅读了其中的记录之后,您可以对其进行处理以逆转替换过程来修复它们。
如果您喜欢在 FileHelpers 类本身中定义所有逻辑,您可以实现 INotifyRead<Transaction>
而不是使用事件。
【讨论】:
以上是关于FileHelpers 在字段中引用和逗号的主要内容,如果未能解决你的问题,请参考以下文章