In another example I had written about how to export from
list of records to excel file. But one of my friends asked me to write a sample
to export from Gridview to excel file.
Here is that function which will export from Gridview to excel
file:
/// <summary>
/// Export Gridview to excel.
/// </summary>
private void
ExportGridviewToExcel()
{
Response.Clear();
Response.AddHeader("content-disposition",
"attachment;filename= Test_Data.xls");
Response.Charset
= "";
Response.ContentType
= "application/vnd.xls";
var stringWriter = new System.IO.StringWriter();
var htmlWriter = new HtmlTextWriter(stringWriter);
// Added gridview to HtmlForm to handle the exception:
// Control 'TestGrid'
of type 'GridView' must be placed
// inside a
form tag with runat=server.
var form = new
System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(TestGrid);
// TestGrid is name of GridView.
// Render Form Control
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
|
Comments
Post a Comment