我有一個 csv 檔案,我正在使用 csvhelper 讀取 csv 檔案。第一行是標題。
RowId Name --> 0the row
----- ----
1 John
2 Smith
3 Mark
4 Tom
我不知道如何為此目的使用 ShouldSkipRecord。如何使用 CSVHelper 直接跳轉到 RowId 3 ?[不洗掉標題] 并從 rowid 4 開始讀取??
這就是我所做的。
CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = true,
Delimiter = ",",
PrepareHeaderForMatch = args => args.Header.ToUpper(),
IgnoreBlankLines = true,
IgnoreReferences = true,
MissingFieldFound = null,
UseNewObjectForNullReferenceMembers = true,
ShouldSkipRecord = row => Convert.ToInt32(row.Row[MyPoint].Skip(0)) <= MyPoint
}; // Mypoint = 3
CsvReader csv = new CsvReader(File.OpenText(FileNameWithPath), csvConfiguration);
csv.Read();
csv.ReadHeader();
while (csv.Read())
{......}
uj5u.com熱心網友回復:
您的ShouldSkip方法需要更多邏輯,因為它需要處理標題、分隔符和 RowId 值。對于所有這些情況,該方法需要正確回傳真或假。
這是滿足要求的一種方法:
// row holds an array of string values of each column in the current row
bool ShouldSkipHandler(string[] row)
{
var rowIdCol = 0;
// sanitize columnValue
var currentRowId = row[rowIdCol].Trim();
// is this the header?
if (currentRowId == "RowId") {
return false;
}
// is this the separator
if (currentRowId.All( c => c == '-')) {
return true;
}
// is this a Rowid
int rowId;
if (Int32.TryParse(currentRowId, out rowId)) {
// is the rowId less than 4?
return rowId < 4;
}
return true;
}
放入此測驗臺時:
var sr = new StringReader(@"RowId , Name
----- , ----
1 , John
2 , Smith
3 , Mark
4 , Tom
");
var csvConfiguration = new CsvHelper.Configuration.CsvConfiguration
{
HasHeaderRecord = true,
Delimiter = ",",
ShouldSkipRecord = ShouldSkipHandler
};
CsvReader csv = new CsvReader(sr, csvConfiguration);
csv.ReadHeader();
while (csv.Read())
{
csv[0].Dump(csv.FieldHeaders[0]); // LinqPad
}
并在 LinqPad 中運行,結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515540.html
上一篇:使用CSV.jl撰寫csv檔案會引發StackOverflowError訊息
下一篇:使用哈希輸出CSV的資料
