Monday, August 18, 2008

Gridview excel export

Some time we have a requirement that we need to export our gridview into the excelsheet.Me have the same requirement so I resolved it as ,I take a image button on the right top of the gridview and on the click of the button I write the following function.

protected void imgBtnExcelExport_Click(object sender, ImageClickEventArgs e)
{

string TempString = string.Empty;
string TempOutput = string.Empty;
Response.Clear();
// ::-> Adding the Header
Response.AddHeader("content-disposition", "attachment;filename=" + this.ReportTitle.Text.Replace(" - "," ").Replace(" ","_").ToString().Trim() + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";

// ::-> Create Stream Write object
System.IO.StringWriter stringWrite = new System.IO.StringWriter();

// ::-> Render controls
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.HtmlTextWriter htmlWritelbl = new HtmlTextWriter(stringWrite);
System.Web.UI.HtmlTextWriter htmlWriteImgLegend = new HtmlTextWriter(stringWrite);
this.ReportTitle.RenderControl(htmlWritelbl);
this.dgReport.RenderControl(htmlWrite);
this.ImgLegend.RenderControl(htmlWriteImgLegend);
Response.Write(stringWrite.ToString(); );
Response.End();
}