Export Gridview to Excel OR Word using Asp.Net
1: Export to Excel
protected void btnExportGridToExcel_Click(object sender, EventArgs e)
{
// It clears all content from the buffer
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment;filename=Students.xls");
//Specify the type that you want to change
//Here we want to change in Excel
Response.ContentType = "application/excel";
System.IO.StringWriter stw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(stw);
gvStudents.RenderControl(htw);
Response.Write(stw.ToString());
Response.End();
}
2: Export to Word Document
protected void btnExportGridToExcel_Click(object sender, EventArgs e)
{
// It clears all content from the buffer
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment;filename=Students.doc");
//Specify the type that you want to change
//Here we want to change in Excel
Response.ContentType = "application/word";
System.IO.StringWriter stw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(stw);
gvStudents.RenderControl(htw);
Response.Write(stw.ToString());
Response.End();
}
Although, When we run project we get error as Control 'gvStudents' of type 'GridView' must be placed inside a form tag with runat=server.
To Remove this error we have to override VerifyRenderingInServerForm() Method.
Although, When we run project we get error as Control 'gvStudents' of type 'GridView' must be placed inside a form tag with runat=server.
To Remove this error we have to override VerifyRenderingInServerForm() Method.
For this type in Visual studio Override VerifyRenderingInServerform() and then hit ENTER key.We will get:
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
base.VerifyRenderingInServerForm(control);
}
Since we don't have any requirement of its implementation so just delete base.VerifyRenderingInServerForm(control);
from above Method. And Your application will work now. :-)
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
base.VerifyRenderingInServerForm(control);
}
Since we don't have any requirement of its implementation so just delete base.VerifyRenderingInServerForm(control);
from above Method. And Your application will work now. :-)
No comments:
Post a Comment