Wednesday, April 16, 2014

Export to Excel form C# code behind



 1. create a gridview and fetch data into it and then
insert this code to button click 

        string FileName = DateTime.Now.ToString();

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename="+FileName+".xls");
        Response.Charset = "";

        // If you want the option to open the Excel file without saving then
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        gvExport.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();

in above code file name is given datetime. 

No comments:

Post a Comment