Export Grid View of .Net to Excel


Dear All,

Here is a new article for exporting your Grid View to Excel. Feel Free to ask your queries. Following are the steps for this:

1. Create a Grid View on Web Page.
2. Bind grid view with data.  For binding of gridview you can refer to the previous article "Dynamic Gridview Bind" Url: http://dinesh-itsolutions.blogspot.in/2010/09/dynamic-gridview-bind.html.

3. After binding the grid view put a button on the web page named "Export to Excel".  On Clicking of that button you can copy and paste the following code.

protected void btnExport(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",                                            "attachment;filename=ExportedFile.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        //To Export all pages
        GridView1.AllowPaging = false;
        this.gridbind();
        GridView1.HeaderRow.BackColor = Color.White;
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
                cell.CssClass = "textmode";
            }
        }
        GridView1.RenderControl(hw);
           
        string style = @"<style> .textmode { } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
}
  //This is necessary event.So do copy/paste this also.
public override void VerifyRenderingInServerForm(Control control)
{
 
}

On Clicking of the button. You can successfully export your grid view to the excel.
Hope you like the article. :-)
 

Comments

Popular posts from this blog

The Page Life Cycle of an ASP.NET and its controls.

Introduction to .NET and .NET Architecture

Embed Tiny Editor in Your Web Application: