在网站上查看 ASPX 时,我得到一个表格,单元格中的文本很少,例如:
tab.Rows[1].Cells[1].innerHtml = "Booked :"
(在很多行和单元格中,但每个单元格中的文本不同)
现在我只想单击一个按钮,表格中的数据将被下载到 Excel 文件中。
表 ID:选项卡
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();
}
修改了 watraplion 答案,但仍然没有回答.. 错误:
DataTable dt = dt; //Use of unassigned local variable 'dt'