簡體   English   中英

我如何找出哪些列的值無效

[英]How do I find out, which columns has invalid value

我正在使用 CsvHelper 來解析 CSV 文件,包括類型轉換,例如到 DateTime。

當單元格值的格式無效時,我得到

while (CsvReader.Read())
{
    var record = CsvReader.GetRecord<TModel>();
    csvReader.GetRecord<MyModel>(); //throws following exception:

    // CsvHelper.ReaderException: 'An unexpected error occurred.'
    // Inner Exception
    //
    // FormatException: The string 'a' was not recognized as a valid DateTime. There is an unknown word starting at index '0'.

我如何找到無法解析的單元格的 HeaderName 或 MyModel 的屬性。

你應該添加一個 try 並且在你的 catch 中你可以使用

int index = csvReader.Context.CurrentIndex; // zero based
int row = csvReader.Context.Row;          // 1 based

然后您可以使用標題記錄獲取您的字段

csvReader.Context.HeaderRecord[index]

加起來它不工作,這就是我是怎么做的

catch (ReaderException e)
{                   
    string notification = $"The field { e.ReadingContext.HeaderRecord[e.ReadingContext.CurrentIndex] } has the invalid value { e.ReadingContext.Record[e.ReadingContext.CurrentIndex] }";                   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM