2

在 aspx 页面中:

<asp:table id = "table1" runat ="server"></table>

我使用 Javascript 从 cs 文件中创建了一个表,如下所示:

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(); 
4

2 回答 2

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"/>
于 2015-05-26T15:39:39.480 回答
-1
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
于 2016-04-11T07:00:22.327 回答