Asp.net-Mvc-3

使用帶有 C# MVC 的 csvhelper (nuGET) 導入 CSV 文件

  • February 25, 2020

通過 NuGet 獲得的https://joshclose.github.io/CsvHelper/用於讀取和寫入 CSV 文件。

CsvHelper 允許您將 CSV 文件直接讀取到您的自定義類中。

如上一個問題所示

var streamReader = // Create a reader to your CSV file.
var csvReader = new CsvReader( streamReader );
List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>();

CsvReader 將根據標題行自動計算出如何匹配屬性名稱(這是可配置的)。它使用編譯的表達式樹而不是反射,因此速度非常快。

它也是非常可擴展和可配置的。

我基本上是在嘗試研究如何讀取帶有標題(未知名稱)的 CSV 文件並將記錄讀入自定義對象。

根本沒有這方面的文件,所以想知道是否有人知道如何使用 CsvReader 將值按順序放入字元串數組中,或者您建議如何處理?

這是我的第一個版本,我會在修改內容並使其更完整時進行更新,但這為我提供了字元串數組中的所有數據。

  [HttpPost]
       public ActionResult UploadFile(HttpPostedFileBase file)
       {

           ICsvParser csvParser = new CsvParser(new StreamReader(file.InputStream));
           CsvReader csvReader = new CsvReader(csvParser);
           string[] headers = {};
           List<string[]> rows = new List<string[]>();
           string[] row;
           while (csvReader.Read())
           {
               // Gets Headers if they exist
               if (csvReader.HasHeaderRecord && !headers.Any())
               {
                   headers = csvReader.FieldHeaders;
               }
               row = new string[headers.Count()];
               for (int j = 0; j < headers.Count(); j++)
               {
                   row[j] = csvReader.GetField(j);
               }
               rows.Add(row);
           }
           ImportViewModel model = new ImportViewModel(rows);
           return View(model);
       }

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