Export Data from DataGrid to Excel file

//on button click event call method  ExportToExcel

protected void btnExport_Click(object sender, EventArgs e)
{
ExportToExcel(gvData,”MyGridData.xls”);
}

//method ExportToExcel having two parameters gridview and filename of excel file
private void ExportToExcel(GridView gvData,string Filename)
{
Response.Clear();
Response.AddHeader(“content-disposition”,string.Format(“attachment; filename={0}”,Filename));
Response.Charset = string.Empty;
// 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);

gvData.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();
}
//very important to override VerifyRenderingInServerForm to ensure that

an HtmlForm control is rendered for the specified ASP.NET server control at run time.

Otherwise gives you an error

Control ‘gvData’ of type ‘GridView’ must be placed inside a form tag with runat=server.

public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s