Saturday, March 6, 2010

Gridview data save to Excel file using ASP.net

Hi
We can simply save or download gridview data to Excel file from our client or browser using this code...

protected void btn_GridtoExcel_Click(object sender, EventArgs e)
{
if (Gridview_barcode.Rows.Count > 0)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";

// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Gridview_barcode.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
else
{
Response.Write("No data found!!");
}

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

No comments: