asp.net-mvc-3 – 使用csvhelper(nuGET)和C#MVC导入CSV文件

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 使用csvhelper(nuGET)和C#MVC导入CSV文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
通过NuGet提供的 http://csvhelper.com用于读取和写入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将值按顺序放入字符串数组中,或者你会如何建议处理这个?

@R_301_323@

这是我的第一个版本,我会更新,因为我修改了一些内容并使其更加完整,但这给了我字符串数组中的所有数据.
[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://www.f2er.com/aspnet/251835.html

猜你在找的asp.Net相关文章