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 alot 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'