Pages

Tuesday, 27 March 2012

Export data to Excel from the Grid View



--> take one button in click event write this code
protected void Excel_Click(object sender, ImageClickEventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "SetaDirectory.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        grdCategory.AllowPaging = false;
        grdCategory.DataBind();
        //Change the Header Row back to white color
        grdCategory.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Applying stlye to gridview header cells
        for (int i = 0; i < grdCategory.HeaderRow.Cells.Count; i++)
        {
            grdCategory.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
        }
        int j = 1;
        //This loop is used to apply stlye to cells based on particular row
        foreach (GridViewRow gvrow in grdCategory.Rows)
        {
            gvrow.BackColor = System.Drawing.Color.White;
            if (j <= grdCategory.Rows.Count)
            {
                if (j % 2 != 0)
                {
                    for (int k = 0; k < gvrow.Cells.Count; k++)
                    {
                        gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                    }
                }
            }
            j++;
        }
        grdCategory.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }


--------------------------------------sriraj--------------------------------------------

No comments:

Post a Comment