使用jQuery将HTML表格导出为MS Excel格式

Export HTML table to MS Excel Format Using jQuery

本文关键字:MS Excel 格式 jQuery HTML 表格 使用      更新时间:2023-09-26

我正试着遵循这个例子。使用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>

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

把这个放到你的表单中

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

用script标签

把它放到header部分
    $(document).ready(function () {
        $("#btnExport").click(function (e) {
            window.open('data:application/vnd.ms-excel,' + $('#container').html());
            e.preventDefault();
        });
    });

我相信你的代码没有错,除了因为你的代码是asp.net。你不能直接使用$('#tbl')。你必须使用 $("#" +'& lt; % = tbl.ClientID %>")