user2357207 user2357207 - 1 month ago 17
ASP.NET (C#) Question

ASP Table to Excel

When viewing ASPX in website, I got a table with few text in the cells, e.g.:

tab.Rows[1].Cells[1].innerHtml = "Booked :"


(In a lot of rows and cells but with different text in each cell)

Now I just want to click a button, and data in the table will be downloaded into an Excel file.

Table ID : tab

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Table tbl = new Table();
TableRow tr = new TableRow();
TableCell tcel = new TableCell();
tcel.Text = "id";
tr.Cells.Add(tcel);

TableCell tcel1 = new TableCell();
tcel1.Text = "id1";
tr.Cells.Add(tcel1);

tab.Rows.Add(tr);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = "ExportExcel.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

//DataGrid dgGrid = new DataGrid();
//dgGrid.DataSource = tbl;
//dgGrid.DataBind();

//Get the HTML for the control.
tab.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}


Modified with watraplion answer, but still not answer..
Error at:

DataTable dt = dt; //Use of unassigned local variable 'dt'

Answer

Try this :

aspx Design View :

<body>
   <form id="form1" runat="server">
      <div>
          <asp:Table ID="Table1" runat="server">
           </asp:Table>
      </div>
      <div>
           <asp:Button ID="btnExport" onclick="btnExport_Click" Text="Export" runat="server">
      </div>
   </form>
</body>

aspx.cs ( code behind )

    protected void Page_Load(object sender, EventArgs e)
    {
        TableRow tr = new TableRow();
        TableCell tcel = new TableCell();
        tcel.Text = "id";
        tr.Cells.Add(tcel);

        TableCell tcel1 = new TableCell();
        tcel1.Text = "id1";
        tr.Cells.Add(tcel1);

        Table1.Rows.Add(tr);
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        string filename = "ExportExcel.xls";
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

        //Get the HTML for the control.             
        Table1.RenderControl(hw);
        //Write the HTML back to the browser.
        //Response.ContentType = application/vnd.ms-excel;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
        this.EnableViewState = false;
        Response.Write(tw.ToString());
        Response.End();
     }