Friday, June 24, 2011

Export to Excel from gridview in c#

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
if (chkall.Checked == true)
{
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "calls report of alluser"+txtfromdate.Text+" "+"to"+" "+txttodate.Text+".xls"));
}
else
{
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "calls report of user" + " " + ddlagent.SelectedItem.Text + ".xls"));
}
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
reportgrid.AllowPaging = false;
getgrid();
//Change the Header Row back to white color
reportgrid.HeaderRow.Style.Add("background-color", "#afabc4");
//Applying stlye to gridview header cells
for (int i = 0; i < reportgrid.HeaderRow.Cells.Count; i++)
{
reportgrid.HeaderRow.Cells[i].Style.Add("background-color", "#afabc4");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in reportgrid.Rows)
{
gvrow.BackColor = Color.White;
if (j <= reportgrid.Rows.Count)
{
//if (j % 2 != 0)
//{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#FFFFFF");
}
//}
}
j++;
}

reportgrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();



}

No comments:

Post a Comment