通过NuGet提供的
http://csvhelper.com用于读取和写入CSV文件.
如下所示在question之前
var streamReader = // Create a reader to your CSV file. var csvReader = new CsvReader( streamReader ); List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>();
CsvReader will automatically figure
out how to match the property names
based on the header row (this is
configurable). It uses compiled
expression trees instead of
reflection,so it’s very fast.It is also very extensible and
configurable.
我基本上试图找出如何读取带有标题(未知名称)的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); }