Export ASP.NET Control to Microsoft Excel
With server-side code, you can bind the ASP.NET control (for example datagrid or repeater) to your data and have the data open in Excel on a client computer with one button-click. To do this, set the ContentType to application/vnd.ms-excel. Also - it is important to set Content-Disposition response header to be "attachment". After that the control is simply rendered with StringWriter and HtmlTextWriter.
- webform markup:
< form id="myForm" method="post" runat="server"> < input type="button" name="btnExcel" value="excel" onclick="navframe.location.href='MyPage.aspx?e=1';"> < iframe type="hidden" src="" style="display:none;" name="navframe">< /iframe> < asp:datagrid id="grdResult" runat="server">< /asp:datagrid> < /form>
- codebehind Page_Load event:
protected System.Web.UI.WebControls.DataGrid grdResult; private void Page_Load(object sender, System.EventArgs e) { grdResult.DataBind(); if (String.Equals(Request.QueryString["e"], "1")) { Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls"); Response.BufferOutput = true; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.Charset = "UTF-8"; EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); grdResult.RenderControl(hw); Response.Write(tw.ToString()); Response.End(); } }
Please note a small trick how iframe is used in this sample to redirect response and get really flexible and reliable UI.
Saturday, April 24, 2004 1:39 AM