public static void ExportGridViewToExcel(string strFileName, DataTable dt, System.Web.HttpResponse response)
{
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
System.Web.UI.WebControls.DataGrid dgGrid = new System.Web.UI.WebControls.DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
////Write the HTML back to the browser.
////Response.ContentType = application/vnd.ms-excel;
//response.ContentType = "application/vnd.ms-excel";
//response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls");
//response.Write(tw.ToString());
//response.End();
byte[] bytes = System.Text.Encoding.Default.GetBytes(tw.ToString());
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
response.Buffer = true;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.ContentType = "application/vnd.ms-excel";
response.ContentEncoding = System.Text.Encoding.Unicode;
response.AddHeader("content-disposition", "attachment; filename=" + strFileName + ".xls");
response.BinaryWrite(bytes); // create the file
response.End(); // send it to the client to download
}