2015年6月23日 星期二

export grid to excel in asp.net when the grid in ContentPlaceHolder

---
   using System.IO;
   public override void VerifyRenderingInServerForm(Control control)
{
    /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
       server control at run time. */
}



protected void btnExoprtExcel_Click(object sender, EventArgs e)
{
    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.xls"));
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    GV1.AllowPaging = false;
    //Change the Header Row back to white color
    GV1.HeaderRow.Style.Add("background-color", "#000000");
    //Applying stlye to gridview header cells
    for (int i = 0; i < GV1.HeaderRow.Cells.Count; i++)
    {
        GV1.HeaderRow.Cells[i].Style.Add("background-color", "#000000");
    }
    int j = 1;
    //This loop is used to apply stlye to cells based on particular row
    foreach (GridViewRow gvrow in GV1.Rows)
    {

        if (j <= GV1.Rows.Count)
        {
            if (j % 2 != 0)
            {
                for (int k = 0; k < gvrow.Cells.Count; k++)
                {
                    gvrow.Cells[k].Style.Add("background-color", "#FFFFFF");
                }
            }
        }
        j++;
    }
    GV1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();
}

沒有留言:

張貼留言