csvhelper通过的NuGet可用于读取和写入的CSV文件。
CsvHelper可以读取你的CSV文件直接到您的自定义类。
由于以下是在previous question
VAR的StreamReader = //创建一个读者CSV文件。VAR csvReader =新CsvReader(StreamReader的);清单< MyCustomType> MYDATA的= csvReader.GetRecords< MyCustomType>();
CsvReader会自动身影 如何匹配属性名称 基于所述标题行(这是 配置)。它使用编译 前pression树,而不是 反射,所以它的速度非常快。
这也是非常可扩展的, 可配置的。
基本上,我试图找出如何在CSV读取头(姓名不详)文件和读取记录到一个自定义对象。
有没有这方面的文档都这样,如果有人知道如何使用CsvReader把值才能到字符串数组或不知道你会如何建议处理此?
解决方案这是我的第一个版本,我将更新为我修改的东西,使之更加完善,但是这给了我所有的数据字符串数组。
[HttpPost] 公众的ActionResult UploadFile(HttpPostedFileBase文件) { ICsvParser csvParser =新CsvParser(新的StreamReader(file.InputStream)); CsvReader csvReader =新CsvReader(csvParser); 的String []标题= {}; 清单<字符串[]>行=新的List<字符串[]>(); 字符串[]行; 而(csvReader.Read()) { //如果它们存在获取头 如果(csvReader.HasHeaderRecord&放大器;&放大器;!headers.Any()) { 标题= csvReader.FieldHeaders; } 行=新的字符串[headers.Count()]; 对于(INT J = 0; J< headers.Count(); J ++) { 行[J] = csvReader.GetField(J); } rows.Add(行); } ImportViewModel模式=新ImportViewModel(行); 返回查看(模型); }csvhelper available via NuGet is used to read and write CSV files.
CsvHelper allows you to read your CSV file directly into your custom class.
As following was shown in a previous 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.
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文件
发布评论