Click here to Skip to main content
15,900,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to export dataset to excel. I tried but it is not generating any file..

C#
public void ExportDataSetToExcel(DataSet ds, string filename)
        {
            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object   
            response.Clear();
            response.Charset = "";

            // set the response mime type for excel   
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

            // create a string writer   
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid   
                    DataGrid dg = new DataGrid();
                    dg.DataSource = ds.Tables[0];

                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }

        }
Posted
Updated 25-Feb-12 0:04am
v2
Comments
Michel [mjbohn] 25-Feb-12 6:03am    
Unchecked checkBox "Treat my content as plain text, not as HTML"

Try adding below code in your code behind :

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}


Also refer below link:
http://toniyojackson.blogspot.in/2010/10/gridview-export-to-excel.html[^]
 
Share this answer
 
hi in which event you are calling this function?
Actually before the page load event it should be called.
Otherwise it will not work.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900