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

标签 asp.net-mvc-3 csv csvhelper import-from-csv

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/

相关文章:

python - 如何限制 CSV 中处理的行数

python - 计算目录中多个csv文件的列数

python - 使用 tweepy 时出现此错误

c# - 使用 CSVHelper 映射 IEnumerable 属性

asp.net-mvc-3 - 将文本附加到 Razor 中的 MvcHtmlString

javascript - Jquery 上传 - MVC 文件名不起作用

asp.net-mvc-3 - Windows 身份验证在 IIS 7.5 中不起作用

ASP.NET MVC 应用程序设置 loginUrl 接受

c# - 使用 CSVHelper 映射空列

c# - CsvWriter,CS1503 参数 2 : cannot convert CultureInfo