TechShri from Shriniwas Wani

Custom Search

22 June, 2006

Want to Export Datagrid content to Excel File ?

I was searching optimized code for exporting datagrid content to .xsl file.. And finally got it...

In .aspx page - put a link like this >>
<
asp:LinkButton text="Export 2 Excel" runat="server" id="btnXport2Excel" onclick="btnXport2Excel_Click">
/>
And Datagrid
<
asp:DataGrid runat="server" id="dgXport2Excel">
/>

And in codebehind .cs file, bind the datagrid in Page_Load() event, and call following function on the click of link >>

protected void btnXport2Excel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader( "content-disposition", "attachment;filename=FileName.xls" );
Response.Charset = "" ;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls" ;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
dgXport2Excel.RenderControl(hw);
Response.Write( stringWrite.ToString() );
Response.End();

}