Когда я пытаюсь экспортировать результаты gridview в виде .xls, он экспортируется только как веб-страница .aspx. Я не уверен, что мне здесь не хватает. Я думаю, что что-то не так на моей странице aspx.cs, но не могу найти это. Это может быть в моем методе «ExportGridToExcel». Я попытался сделать простой поиск в Google для других людей, сталкивающихся с той же самой проблемой, и нашел только одну статью, но это не помогло мне.
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();
}
}
}