Skip to main content

Convert Generic List to CSV

In my recent development with c#, I have to code for the functionality to Convert one Generic list of class XYZ to CSV downloadable File with dynamically suppress some of the column and different descriptive headers then the properties name for the column.

So I develop one Generic function which will convert List to CSV and return the string, which will then wrapped to Http Response to available as downloadable file.

Here is a Function which will convert List of Generic type T to CVS format string with 2 arguments. First Argument is List of objects to be converted into CSV and second is the 2 dimensional string array with the name of properties of object to be include in conversion with the Header Text for that properties to use while it is converting into CSV.

private static string ListToCsv(ref List<T> list, string[,] HeaderAndColumns)
        {
            if (list == null || list.Count == 0) return "";

            Type t = typeof(T);
            int lenght = HeaderAndColumns.GetLength(0);

            StringWriter sw = new StringWriter();

            // Create Header Row..
            for (int l = 0; l < lenght; l++)
            {
                sw.Write(HeaderAndColumns[l, 0].Replace(',', ' '));
                if (l < lenght - 1)
                    sw.Write(",");
            }
            sw.Write(sw.NewLine);

            //this acts as datarow

            foreach (T item in list)
            {
                for (int i = 0; i < lenght; i++)
                {
                    string whatToWrite =
                        Convert.ToString(item.GetType().GetProperty(HeaderAndColumns[i, 1]).GetValue(item, null)).Replace(',', ' ');

                    if (i < lenght - 1)
                        whatToWrite += ",";

                    sw.Write(whatToWrite);
                }
                sw.Write(sw.NewLine);
            }

            return sw.ToString();
        }

If we have class XYZ as follow

public class XYZ
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
    }

And we want to convert list of XYZ's object (List<XYZ>) to CSV we have to call the function like following

// 2D string arry , 1st is header , 2nd is Property name
    string[,] HeaderAndColumns = new string[,] {
            {"Header 1",      "prop1"},
            {"Header 2","prop2"}
            };

string strCSV = ListToCsv(ref list, HeaderAndColumns);

To warp is with Http Response you can use following code. This will help you to through the converted CSV string as downloadable file.

HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", filename));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter objSw = new StringWriter())
            {
                   string[,] HeaderAndColumns = new string[,] {
                        {"Header 1",      "prop1"},
                        {"Header 2","prop2"}
                        };
                  objSw.Write(ListToCsv(ref list, HeaderAndColumns));
                  HttpContext.Current.Response.Write(objSw.ToString());
                HttpContext.Current.Response.End();
            }

Popular posts from this blog

LINQ union with group by

In my recent development activity with LINQ query, I need to get the some of user points from tow different tables where user's points are based on some activities. There are many users who are into one table but not in another table and some are in both table. For example tables having data like this Table 1 UserID   Points 1           10 2           20 Table 2 UserID    Points 2           20 3           30 Result should be UserID    Points 1           10 2           40 3           30 I try to get this result with LINQ query using joins and group by samples from the web. I had googling to get something useful but dont get any success. So I try with new logic and here it is, I think it will help full to other also. Example Item class to use public class Item {   public int ID { get ; set ; }   public int Total { get ; set ; }   public Item()   {   }   public Item( int ID, int Total)   {     this .ID = ID; this .Total = Total;   }

SqlConnection from ObjectContext.Connection

Following is C# code to get the  SqlConnection from ObjectContext.Connection . This is usefully to run dynamically created query using ADO.NET using connection string specified into the EDMX ObjectContext object. C# Code Example : using ( EntityContext context = new EntityContext ()) { EntityConnection ec = ( EntityConnection )context.Connection; SqlConnection sc = ( SqlConnection )ec.StoreConnection; SqlDataAdapter da = new SqlDataAdapter (strQuery, sc); DataSet ds = new DataSet (); da.Fill(ds); return ds.Tables[0]; }

Get Tables and Columns Names by LINQ

Here I am explaining one of the tricks to get all table name list along with column of it from your DataContext. I am using the System.Data.Linq.Mapping.MetaModel to get information about tables and it have much more database related information. Following are the code to list all table name along with column from your DataContext. //DataContext object. DataClassesDataContext DB = new DataClassesDataContext ();         //String variable to stor html to render. string strHtmlToLoad = "" ;         //Heading strHtmlToLoad = "<-h2->Table Names<-/h2-><-ol->" ;         //Loop through tables add name to string foreach ( var mTable in DB.Mapping.GetTables()) { strHtmlToLoad += "<-li->" + mTable.TableName + "<-ul->" ; //Loop through table's columns add name to string foreach ( var mColumn in mTable.RowType.DataMembers) strHtmlToLoad += "<-li->