When I try to export my gridview results as an .xls it is only exporting it as an .aspx webpage. I am not sure what I am missing here. I think there is something wrong in my aspx.cs page but can't find it. It might be in my "ExportGridToExcel" method. I have tried to do some simple googling for other people running into the same issue and only found one article but it did not help me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Dynamic;
namespace crifaccess
{
public partial class Application : System.Web.UI.Page
{
private SqlConnection con;
private SqlCommand com;
private string constr, query;
private void connection()
{
constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
con = new SqlConnection(constr);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindgrid();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void Bindgrid()
{
connection();
query = "ApplicationPageSSN";
com = new SqlCommand(query, con);
GridView2.DataBind();
con.Close();
}
protected void ExcelExport_Click (object sender, EventArgs e)
{
ExportGridToExcel();
}
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "CRIF" + DateTime.Now+".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filname=" + FileName);
GridView2.GridLines = GridLines.Both;
GridView2.HeaderStyle.Font.Bold = true;
GridView2.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
}
}