Wednesday, October 17, 2012

Fluent CSV/XML Exporter for Lists/IEnumerable<T>'s

CodeProject - Fluent CSV/XML Exporter for List

"I don't know about you, but I work with lots and lots of lists at work and from time to time, I have the requirement to export some List<T> to a CSV file, and I used to just write a little helper method that use a bit of Reflection that got out all the public properties of the T objects stored in my list and then get the names of the properties and use those as headers, and then go through the List<T> and get the values out using some Reflection over the properties.

This works fine, but it is just not that generic a solution, and only really worked with that particular type of T that I was storing in the list, and all the code to decide what columns to use and what the column headers should be was hidden away from the users of the method that did the export.

So I had a think about this and thought there must be a better way, so this article represents a generic solution to this problem where I can do the following:

  1. Could be used as an extension method to any IEnumerable<T>
  2. Let the using code specify what columns should be exported
  3. Use a Fluent API (as they are all the rage these days)
  4. Allow auto header named to be obtained using Expression trees
  5. Allow the the user to supply custom header names
  6. Allow the user to also supply custom format strings for the data being exported
  7. Allow the data to be exported to a CSV file or allow the data to be exported to a CSV string
  8. Allow the exporter to be able to deal with NULL values
  9. Allow the user to specify a custom separator (if none is supplied, a comma "," is used)



I came across this today and wanted to make sure I captured it here in my remote full text memory store (oh, and share it with you too... um... yeah... ;)

I spent a few hours dealing with saving an ObservableCollection<T> to a CSV and really, really didn't want to roll my own. But I needed any method I used to be customizable, letting me select columns, apply headers (with also letting me override the default headers with my own), letting me customize my formatting (such as letting me pick which values/columns were quote delimited), where I wasn't spending days re-inventing this wheel, and in the end, wasn't a pain to use.

Enter Sacha's awesome "Fluent CSV/XML Exporter for List" project. With this a few lines of my code I got exactly the output I needed, without any tweaks to my existing objects.

MAN, I love the internet... Sacha, you rock, thank you for sharing... :)

1 comment:

Phil Bolduc said...

I have used Josh Close's CsvHelper (CsvHelper on GitHub) before. It has great import and export features.