Pages

Dec 18, 2008

how to Export Grid view To Excel + Asp.Net 2.0 + C#

The below code Exports the Grid view to Excel in C#.

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

///
/// Exports Grid To Excel
///

private void ExportToExcel(GridView gv)
{
StringWriter stw = null;
HtmlTextWriter htextw = null;
string fileName = string.Empty;

fileName = "Test";
try
{
HtmlForm form = new HtmlForm();
string attachment = "attachment; filename=" + fileName + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.Buffer = true;
stw = new StringWriter();
htextw = new HtmlTextWriter(stw);
form.Controls.Add(gv);
this.Controls.Add(form);
form.RenderControl(htextw);
Response.Write(stw.ToString());
gv.Columns[10].Visible = true;
Response.End();
}
finally
{
stw = null;
htextw = null;
}
}


This code will open a open or Save dialog to open or save the .xls files created.

No comments: