Search

Export ASP.NET to Excel

using System;
using System.IO;
using System.Configuration;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
 protected void Button1_Click(object sender, EventArgs e)
 {
  try
  {
   Response.Clear();
   Response.Buffer = true;
   Response.AddHeader("content-disposition", "attachment;filename=gridviewdata.xls");
   Response.Charset = "";
   Response.ContentType = "application/vnd.ms-excel";
   StringWriter sWriter = new StringWriter();
   HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);
   GridView1.RenderControl(hWriter);
   Response.Output.Write(sWriter.ToString());
   Response.Flush();
   Response.End();
  }
  catch (Exception ex)
  {
   Label1.Text = ex.ToString ();
  }
 }

 public override void VerifyRenderingInServerForm(Control control)
 {
 }
}