Export Datagrid Gridview to Excel CSV format on the fly in asp.net

First need to bind grid control( Gridview, Datagrid, Datalist, repeater).  I used the current UTC datetime as name if downloaded file. when Download PopUp will open user can save that file anywhere on his local drive. In this example, you can also see how to show "DownLoad PopUp" in asp.net on the Fly. No need to place control in aspx page. Just create the data control at runtime and bind with data.

 private  void ExportToExcel()
{

 SqlDataAdapter adpgetData = new SqlDataAdapter("Your DB Query", ConfigClass.DbConn);
                    DataSet dsGetData = new DataSet();
                    adpgetData.Fill(dsGetData);
                    if (dsGetData.Tables[0].Rows.Count > 0)
                    {
                        DataGrid dg = new DataGrid();
                        dg.DataSource = dsGetData.Tables[0];
                        dg.HeaderStyle.BackColor =System.Drawing.Color.FromName("#c0c0c0");
                        dg.HeaderStyle.ForeColor = System.Drawing.Color.FromName("#000000");
                        dg.HeaderStyle.Font.Bold = true;// = Color.FromName("#000000");
                        dg.DataBind();
                      string reportName = Convert.ToString(DateTime.UtcNow).Replace("/", "_").Replace(" ", "_").Replace(":", "_");
        ExportGridView(dg, reportName);
                   }

}

 private  void ExportGridView(DataGrid dg, string reportName)
    {
        Response.AddHeader("Content-Disposition", "attachment;filename=" + reportName + ".xls");
        Response.AddHeader("Status", "200 OK");
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(Encoding.Unicode.GetPreamble());
        Response.ContentType = "application/vnd.ms-excel";
        //dg.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        dg.RenderControl(hw);
        Response.Write(RenderGridView(dg));
        Response.End();
    }
    public  string RenderGridView(DataGrid dg)
    {
        string returnvalue = string.Empty;
        try
        {
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(stringWrite);
             VerifyRenderingInServerForm(dg);
            dg.RenderControl(writer);
            returnvalue = writer.InnerWriter.ToString();
        }
        catch (Exception ex)
        {

        }
        return returnvalue;
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        return;
    }
 

Related Alrticles

Add Your Business in Free Listing


FREE!!! Registration