Create a CSV File from a .NET Generic List
Submitted by brian on Tue, 12/02/2008 - 5:09am.
Here's a method I've been working on for a recent project. It will make a csv file from a generic list of type <T>.
There are methods out there for doing similar with DataTables... I like working with generic lists myself.
It does what it needs to do, but I'm not terribly happy with it yet, especially with a class with multiple constructors (all properties are used in csv).
(sorry about the formatting... gotta find a c# code format plugin...)
UPDATE: http://drupal.org/project/geshifilter
/// <summary> /// Creates the CSV from a generic list. /// </summary>; /// <typeparam name="T"></typeparam>; /// <param name="list">The list.</param>; /// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>; public static void CreateCSVFromGenericList<T>(List<T> list, string csvNameWithExt) { if (list == null || list.Count == 0) return; //get type from 0th member Type t = list[0].GetType(); string newLine = Environment.NewLine; using (var sw = new StreamWriter(csvNameWithExt)) { //make a new instance of the class name we figured out to get its props object o = Activator.CreateInstance(t); //gets all properties PropertyInfo[] props = o.GetType().GetProperties(); //foreach of the properties in class above, write out properties //this is the header row foreach (PropertyInfo pi in props) { sw.Write(pi.Name.ToUpper() + ","); } sw.Write(newLine); //this acts as datarow foreach (T item in list) { //this acts as datacolumn foreach (PropertyInfo pi in props) { //this is the row+col intersection (the value) string whatToWrite = Convert.ToString(item.GetType() .GetProperty(pi.Name) .GetValue(item, null)) .Replace(',', ' ') + ','; sw.Write(whatToWrite); } sw.Write(newLine); } } }
So there you have it... C# generic list to csv file!
Couple things to change/ideas...
- take in a delimiter (string) (comma is standard now, but it could be anything, use that as .Replace() of value as well)
- remove last comma in header row.
- fix this line 'Type t = list[0].GetType();' (I don't like it!)
Any suggestions are welcome!
Tags:

















This is really nice to have in my bag of tricks now! Thanks for sharing! It's the kind of thing you never know when you'll need it, but saves the day when it does.
- reply
Submitted by Duncan (not verified) on Thu, 12/04/2008 - 11:44am.thanks!
- reply
Submitted by brian on Tue, 12/02/2008 - 2:03pm.Replace: 'Type t = list[0].GetType();' with typeof(T);
- reply
Submitted by Anonymous (not verified) on Tue, 12/02/2008 - 6:32am.