本文介绍了使用csvhelper(的NuGet)用C#MVC导入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用于读取和写入的CSV文件。
CsvHelper可以读取你的CSV文件直接到您的自定义类。
由于以下是在previous question
VAR的StreamReader = //创建一个读者CSV文件。
VAR csvReader =新CsvReader(StreamReader的);
清单< MyCustomType> MYDATA的= csvReader.GetRecords< MyCustomType>();
I'm basically trying to work out how to read in a CSV file with headers (unknown names) and read the records into a custom object.
There is no documentation on this at all so wondered if anyone knew how to use CsvReader to put the values in order into an array of strings or how would you recommend dealing with this?
解决方案
This is my first version, I will update as I amend things and make it more complete but this gives me all the data in string arrays.
[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);
}
这篇关于使用csvhelper(的NuGet)用C#MVC导入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!