Anatoly Lubarsky

Logo
MSSQL, .NET, Design. Life and Music

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.


Related Posts:

Saturday, April 24, 2004 1:39 AM

Comments

# re: HowTo: Export control to Excel.
I get a blank excel file. I wonder if it is because my datagrid is bound to a datareader rather than a datasource. hmm

8/2/2004 10:25 PM by steve

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)