Wednesday, September 30, 2009

Export ASP.NET GridView to Excel


















protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

BindData();

}

}
private void BindData()

{

string constr = @"Data Source=XYZ;Initial Catalog=testdatabase;Persist Security Info=True;User ID=ABC;Password=abcdefg;";

string query = "SELECT * From emp1";

SqlDataAdapter da = new SqlDataAdapter(query, constr);

DataTable table = new DataTable();

da.Fill(table);

GridView1.DataSource = table;

GridView1.DataBind();

}

protected void btnExcelReport_Click(object sender, EventArgs e)

{

Response.Clear();

Response.AddHeader("content-disposition", "attachment; filename=UserRecord.xls");

Response.Charset = "";

Response.ContentType = "application/vnd.xls";

StringWriter stringWriter = new StringWriter();

HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

GVExamUserSearchList.RenderControl(htmlWriter);

Response.Write(stringWriter.ToString());

Response.End();

}

Sometimes, when you render any asp.net control dynamically as I am doing with the GridView control in this tutorial, you can get HttpException with the following message:


Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.


The problem can be solved by overriding Page class VerifyRenderingInServerForm method which confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

public override void VerifyRenderingInServerForm(Control control)

{ }


When you will click the Export to Excel button you will see the following dialog box asking you to open or save dynamically generated Excel file.

















No comments:

Post a Comment