Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Monday, January 31, 2011

Exporting HTML Table in Excel

  protected void Button1_Click(object sender, EventArgs e)
    {
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=myexcel.xls");
        HttpContext.Current.Response.Charset = "";
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        table1.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
   }

Here is the code sample for table
     <table id="table1" runat="server">
        <tr><td></td></tr>
         ...
         ......
        <tr><td></td></tr>
   </table>
set  EnableEventValidation="false" to your page directive

ex :
   <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ToExcel.aspx.cs" Inherits="ToExcel"     EnableEventValidation="false" %>

Put This Method Inside a page :
public override void VerifyRenderingInServerForm(Control control)
    {

    }

No comments:

Post a Comment