Skip to main content

Export gridview data to csv file..



Following is the function in c# which will export passed gridview to csv file. Note that this function not work if gridview have Autogeneratedcolumn property to true, to make it dynamic you have to add column through code, how to do that see category Gridview posts.


public static void ExportToCsv(string fileName, GridView gv,string Title)
{
            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())
            {

                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;
                objSw.Write("Report:  " + Title + "");
                objSw.Write(objSw.NewLine);
                objSw.Write("Report Date: "+DateTime.Now.ToString());
                objSw.Write(objSw.NewLine);
                objSw.Write(objSw.NewLine); objSw.Write(objSw.NewLine);

                //  add the header row to the table
                int NoOfColumn = gv.Columns.Count;
                //Create Header
                for (int i = 0; i < NoOfColumn; i++)
                {
                    objSw.Write(gv.Columns[i].HeaderText);
                    //check not last column
                    if (i < NoOfColumn - 1)
                    {
                        objSw.Write(",");
                    }
                }

                objSw.Write(objSw.NewLine);


                //Create Data
                foreach (GridViewRow dr in gv.Rows)
                {
                    for (int i = 0; i < NoOfColumn; i++)
                    {
                        objSw.Write(PrepareControlForExportToCsv(dr.Cells[i]).Replace(",",""));

                        if (i < NoOfColumn - 1)
                        {
                            objSw.Write(",");
                        }
                    }
                    objSw.Write(objSw.NewLine);
                }


                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(objSw.ToString());
                HttpContext.Current.Response.End();
            }
}


private static string PrepareControlForExportToCsv(Control control)
{
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is Literal)
                {
                    return (current as Literal).Text;
                }
                else if (current is Label)
                {
                    return (current as Label).Text;
                }
              
                if (current.HasControls())
                {
                    GridViewExportUtil.PrepareControlForExportToCsv(current);
                }
            }
            if (control is TableCell)
                return (control as TableCell).Text;
            else
                return "";
}

Comments

Popular posts from this blog

MongoDB - How to reduce storage size after deleting documents on replica set?

MongoDB does not free the disk space for OS use after deleting bunch of documents from the collection. We can reclaim that space using following cases. By using compact command - Can be run on collections, but block all orations on database, need small downtime By using repaireDatabase - Run on database need extra space and serious downtime By dumping database and than drop and restore it - Time consuming and need downtime By copy database using temporary name drop original and then re copy with original name - Time consuming and need downtime Following is the best method of achieve same without downtime on replica set Step down secondary server Delete database files Start server, It will start Replica Set Initial Sync. After sync over do the same with other secondary servers one by one For primary server step it down. Make sure one of the secondary become primary Delete database file on primary Start primary server It will start Replica Set Initial Sync. After R...

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 cla...

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]; }