1

我正在尝试遵循这个例子。使用 jQuery 将 HTML 表格导出为 MS Excel 格式。

这是我的.aspx:

<head runat="server">
    <title></title>
    <script src="Scripts/jQuery.1.8.3.js" type="text/javascript"></script>
    <script src="Scripts/JScript2.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Table ID="tbl" runat="server">
        </asp:Table>
        <input type="button" id="btnExport" value=" Export Table data into Excel " />
    </div>
    </form>
</body>

.js (JScript2.js):

$("#btnExport").click(function (e) {
    window.open('data:application/vnd.ms-excel,' + $('#tbl').html());
    e.preventDefault();
});

...以及背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JQuery_Export_To_Excel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TableRow tr = new TableRow();
        TableCell tc = new TableCell();

        tc.Text = "AAA";
        tr.Cells.Add(tc);

        tc = new TableCell();
        tc.Text = "BBB";
        tr.Cells.Add(tc);

        tbl.Rows.Add(tr);    
    }
}

生成的页面源:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title>
    <script src="Scripts/jQuery.1.8.3.js" type="text/javascript"></script>
    <script src="Scripts/JScript2.js" type="text/javascript"></script>
</head>
<body>
    <form method="post" action="JQuery_Export_To_Excel.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2NTA0OTEwODdkZKr9kRtjn1C5sAo2woCwfF/8uHOVcyNi1bu4OtVBNKlS" />
</div>

<div class="aspNetHidden">

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAIdFUHUqRwMmhFieKB52uC8avDSflAS9b8PVcR1BxTTBqeDRyg6lH5NKPWh6Jt5ee2zX+bYNkguHBdZjCzKvoJa" />
</div>
    <div>
        <table id="tbl">
    <tr>
        <td>AAA</td><td>BBB</td>
    </tr>
</table>
        <input name="btnExport" type="button" id="btnExport" value=" Export Table data into Excel " />
    </div>
    </form>
</body>
</html>

我不知道我做错了什么,但是当我单击btnExport时,什么也没有发生。我该如何解决这个问题?

4

2 回答 2

1

把它放在你的表格中

<div>
    <div id="container">
        <asp:Table ID="tbl" runat="server">
        </asp:Table>
    </div>
    <input type="button" id="btnExport" value=" Export Table data into Excel " />
</div>

把它放在带有脚本标签的标题部分

    $(document).ready(function () {
        $("#btnExport").click(function (e) {
            window.open('data:application/vnd.ms-excel,' + $('#container').html());
            e.preventDefault();
        });
    });
于 2012-12-21T23:26:16.233 回答
0

我相信您的代码没有任何问题,只是因为您的代码是 asp.net。你不能直接使用 $('#tbl') 。你必须使用 $("#" +'<%=tbl.ClientID%>')

于 2012-12-21T22:26:23.893 回答