ClosedXML library, described in the previous post, allows reach manipulations with Excel spreadsheets, however sometime all what is need by the application is to quickly import/export some data. In this CSV, as a lighter format, may be handier.

CSVHelper is a simple library which allows to work with CSV file in a strongly-typed manner and eliminates the need of manually parsing the text.

Exporting data to CSV

public class Animal
{
   public string Name { get; set; }
   public string Color { get; set; }
   public int Age { get; set; }

   public static void ExportToCsv(string fileName, IEnumerable animals)
   {
      using (var textWriter = new StreamWriter(fileName))
      using (var csv = new CsvWriter(textWriter))
      {
         csv.WriteRecords(animals);
      }
   }
}

In addition to storing the rows as the batch, library allows to store them one-by-one, which is useful for the large number of rows:

csv.WriteRecord(animal);
csv.NextRecord();

Reading CSV

Reading of information from CSV is equally simple:

public static IEnumerable ImportFromCsv(string fileName)
{
   using (var textReader = new StreamReader(fileName))
   using (var csv = new CsvReader(textReader))
   {
      return csv.GetRecords();
   }
}

Similar to writing to CSV, reading from CSV can be performed row-by-row as well.

blog comments powered by Disqus