https://joshclose.github.io/CsvHelper/可通过 NuGet 获取,用于读取和写入 CSV 文件。
CsvHelper 允许您将 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);
}
关于asp.net-mvc-3 - 使用 csvhelper (nuGET) 和 C# MVC 导入 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5496845/