Few days ago someone asked me that how
we can export the GridView control to Excel. The GridView control is
inside the FormView control. Check out the complete code below
for the solution.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
DataSet ds = new DataSet();
if (Cache["DataSet"] == null)
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT
* FROM Users", myConnection);
ad.Fill(ds);
Cache["DataSet"] = ds;
}
fv1.DataSource = (DataSet)Cache["DataSet"];
fv1.DataBind();
FormViewRow row = fv1.Row;
GridView gv = row.FindControl("gv1") as GridView;
gv.DataSource = (DataSet) Cache["DataSet"];
gv.DataBind();
}
private GridView GetGridView()
{
fv1.DataSource = Cache["DataSet"] as DataSet;
fv1.DataBind();
FormViewRow row = fv1.Row;
GridView gv = row.FindControl("gv1") as GridView;
gv.DataSource = Cache["DataSet"] as DataSet;
gv.DataBind();
return gv;
}
private string ConnectionString
{
get { return @"Server=localhost;Database=School;
Trusted_Connection=true"; }
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition",
"attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// 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 gv1 = GetGridView();
gv1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
the specified ASP.NET server control at run time.
}
}
powered by IMHO 1.3