Dot-Net

在 .NET 中解析分隔的 CSV

  • April 10, 2009

我有一個以逗號分隔格式的文本文件,由"大多數欄位分隔。我正在嘗試將其轉化為可以枚舉的內容(例如,通用集合)。我無法控製文件的輸出方式,也無法控制它用於分隔符的字元。

在這種情況下,欄位用逗號分隔,文本欄位用"標記括起來。我遇到的問題是某些欄位中有引號(即 8 "Tray),並且不小心被選為下一個欄位。在數字欄位的情況下,它們周圍沒有引號,但它們確實以 + 或 - 符號開頭(表示正數/負數)。

我正在考慮一個 RegEx,但我的技能不是那麼好,所以希望有人能提出一些我可以嘗試的想法。這個文件中有大約 19,000 條記錄,所以我試圖盡可能高效地完成它。以下是幾個範例數據行:

"00","000000112260   ","Pie Pumpkin                             ","RET","6.99 ","     ","ea ",+0000000006.99000
"00","000000304078   ","Pie Apple caramel                       ","RET","9.99 ","     ","ea ",+0000000009.99000
"00","StringValue here","8" Tray of Food                             ","RET","6.99 ","     ","ea ",-00000000005.3200

還有很多領域,但你可以得到圖片….

我正在使用 VB.NET,並且我有一個通用的列表設置來接受數據。我曾嘗試使用CSVReader,它似乎執行良好,直到您達到第三條記錄(在文本欄位中帶有引號)。如果我能以某種方式讓它處理額外的引號,那麼 CSVReader 選項會很好用。

謝謝!

這裡

Encoding fileEncoding = GetFileEncoding(csvFile);
// get rid of all doublequotes except those used as field delimiters
string fileContents = File.ReadAllText(csvFile, fileEncoding);
string fixedContents = Regex.Replace(fileContents, @"([^\^,\r\n])""([^$,\r\n])", @"$1$2");
using (CsvReader csv =
      new CsvReader(new StringReader(fixedContents), true))
{
      // ... parse the CSV

我建議查看 .Net 中的TextFieldParserClass。你需要包括

Imports Microsoft.VisualBasic.FileIO.TextFieldParser

這是一個快速範例:

       Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
       Dim CurrentRecord As String() ' this array will hold each line of data
       afile.TextFieldType = FileIO.FieldType.Delimited
       afile.Delimiters = New String() {","}
       afile.HasFieldsEnclosedInQuotes = True

       ' parse the actual file
       Do While Not afile.EndOfData
           Try
               CurrentRecord = afile.ReadFields
           Catch ex As FileIO.MalformedLineException
               Stop
           End Try
       Loop

引用自:https://stackoverflow.com/questions/736629