Reading CSV files using C#

后端 未结 12 2487
野的像风
野的像风 2020-11-21 22:49

I\'m writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For ex

12条回答
  •  渐次进展
    2020-11-21 23:26

    Another one to this list, Cinchoo ETL - an open source library to read and write CSV files

    For a sample CSV file below

    Id, Name
    1, Tom
    2, Mark
    

    Quickly you can load them using library as below

    using (var reader = new ChoCSVReader("test.csv").WithFirstLineHeader())
    {
       foreach (dynamic item in reader)
       {
          Console.WriteLine(item.Id);
          Console.WriteLine(item.Name);
       }
    }
    

    If you have POCO class matching the CSV file

    public class Employee
    {
       public int Id { get; set; }
       public string Name { get; set; }
    }
    

    You can use it to load the CSV file as below

    using (var reader = new ChoCSVReader("test.csv").WithFirstLineHeader())
    {
       foreach (var item in reader)
       {
          Console.WriteLine(item.Id);
          Console.WriteLine(item.Name);
       }
    }
    

    Please check out articles at CodeProject on how to use it.

    Disclaimer: I'm the author of this library

提交回复
热议问题