在aspx页面中:
<asp:table id = "table1" runat ="server"></table>
我使用cs文件中的Javascript创建了一个表格,如下所示:
StringBuilder sb = new StringBuilder()
sb.Append('<script>') ;
sb.Append(document.write('<table><tr><td>hghj</td></tr></table>'))
Table cell ;
Table row;
cell.Control.Add(new LiteralControl(sb.ToString())) ;
row.Control.Add(cell);
table1.Control.Add(row);
现在我想将该表导出为excel,因此我使用了以下代码。它打开了excel文件。但没有看到数据。
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
Response.ContentEncoding = Encoding.UTF8;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
table1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
答案 0 :(得分:0)
我有一个类似的问题,以下解决方案对我有用。希望它有助于OP和其他人。在我的例子中,表数据是在运行时动态填充的,但是当我尝试将数据导出到excel时,我得到一个空白的excel文件。我将表生成代码放在if (!IsPostBack){}
之外解决了这个问题。这是我的代码结构在更改后的样子:
protected void Page_Load(object sender, EventArgs e)
{
FunctionToPopulateTableDataAtRuntime();
if (!IsPostBack)
{
// other parts of the code
}
}
private void FunctionToPopulateTableDataAtRuntime()
{
// code to dynamically populate table data at run-time
// this code is somewhat similar to that of OP
// but it does not make use of JavaScript whatsoever
}
private void ExportTableToExcel()
{
// the code for this function is somewhat similar to what OP has
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
Response.ContentEncoding = Encoding.UTF8;
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myTable.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
ExportTableToExcel();
}
这就是代码前端(aspx)的样子:
<asp:Table
ID="myTable"
runat="server">
</asp:Table>
<asp:Button
ID="btnExportToExcel"
runat="server"
Text=" Export to Excel "
OnClick="btnExportToExcel_Click"/>
答案 1 :(得分:-1)
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}