将HTML表导出为Excel文件

时间:2016-01-22 23:36:34

标签: javascript jquery html excel

我一直在研究一些能够做到这一点的jQuery插件。我决定使用http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html处的那个,并尽可能地遵循其说明。我一直在测试这个插件,但每次单击按钮导出时都没有任何反应。该表使用PHP填充(从MySQL服务器中提取数据),以下是我目前使用的脚本。

<script>
        $(document).ready(function() {

                //activate footable jquery plugin (this is the dynamic table on the report page with search and sorting functions)
                $('.footable').footable();


        });

        //Prepare table2excel plugin (clicking the export button will send the main table to an Excel spreadsheet)
        $("button").click(function(){
            $(".footable").table2excel({
                //Exclude CSS class specific to this plugin
                exclude: ".noExl",
                name: "Excel Document Name"
            });
        });

</script>

添加新代码后,footable显示根本没有变化。我能做什么?我一直在想我只是放错了table2excel块,但即使我把它放在ready(function(){})块内,也没有发生任何事情。

6 个答案:

答案 0 :(得分:1)

正如@charlietfl所说,.click()中需要$(document).ready绑定,因为如果不是,当你尝试绑定它时,该元素不存在。

这样你就不需要使用插件了

function exportGrid(gridID,filename) {
    var html = $('#' + gridID).html();
    var a = document.createElement('a');
    a.id = 'tempLink';
    a.href = 'data:application/vnd.ms-excel,' + html;
    a.download = filename + ".xls";
    document.body.appendChild(a);
    a.click(); // Downloads the excel document
    document.getElementById('tempLink').remove();
}
$(document).ready(function() {
    $("button").click(function(){
        exportGrid("TheGridId","The excel name");
    });
});

这里有一个示例https://jsfiddle.net/0mzn7uLq/

答案 1 :(得分:0)

管理修复它。我最初怀疑没有把它放在准备好的功能中会是一个问题,并认为它会解决问题,但这只是问题的一部分。我也忘了逗号。完成的结果如下。

<script>
    $(document).ready(function() {

        //activate footable jquery plugin (this is the dynamic table on the report page with search and sorting functions)
        $('.footable').footable();

        //Prepare table2excel plugin (clicking the export button will send the main table to an Excel spreadsheet)
        $("button.excelexport").click(function(){
            $("#footable").table2excel({
                //Exclude CSS class specific to this plugin
                exclude: ".noExl",
                name: "Merchandising Report",
                filename: "merchReportTable"
            });
        });

    });            

</script>

答案 2 :(得分:0)

  

这是可用于将HTML表格导出为具有自定义文件名的excel文件的代码。我试过IE11,Firefox 48&amp;铬51。

     
    
        
  1. 在HTML部分中添加<iframe id="txtArea1" style="display:none"></iframe>
  2.     
  3. 添加一个按钮<button id="btnExport" onclick="toExcel_()">Export to excel</button>,它将调用函数&#34; toExcel _()&#34;
  4.        

Ps:我是Stackoverflow的新手,所以请原谅我的回答格式:D

    function toExcel_(){
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('tblExport'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";


        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE"); 
        var dt = new Date();
        var day = dt.getDate();
        var month = dt.getMonth() + 1;
        var year = dt.getFullYear();
        var hour = dt.getHours();
        var mins = dt.getMinutes();
        var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;


    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Report.xls");
    }  
    else // For Chrome and firefox (Other broswers not tested)
    {

        uriContent = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text);


        var sa = document.createElement("a");
        sa.setAttribute("href", uriContent);
        sa.setAttribute("download", "Report"+postfix +".xls");
        document.body.appendChild(sa); // Required for FF

       sa.click();
    }


    return (sa);

}

答案 3 :(得分:0)

&#13;
&#13;
<html>

<head>
  <script src="jquery.min.js"></script>
  <script src="jquery.btechco.excelexport.js"></script>
  <script src="jquery.base64.js"></script>

  <script>
    $(document).ready(function() {
      $("#btnExport").click(function() {
        $("#tblExport1").btechco_excelexport({
          containerid: "tblExport1",
          datatype: $datatype.Table
        });
      });
    });
  </script>
</head>

<body>

  <div id="dvd">
    <table id="tblExport1" style="border:1px solid black; ">
      <thead>
        <tr>
          <th>#</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Username</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td style='background-color:red;'>1</td>
          <td>Mark</td>
          <td>Otto</td>
          <td>@mdo</td>
        </tr>
        <tr>
          <td>2</td>
          <td>Jacob</td>
          <td>Thornton</td>
          <td>@fat</td>
        </tr>
        <tr>
          <td>3</td>
          <td>Larry</td>
          <td>the Bird</td>
          <td>@twitter</td>
        </tr>
        <tr>
          <td>4</td>
          <td>Larry</td>
          <td>the Bird</td>
          <td>@twitter</td>
        </tr>
      </tbody>
    </table>
  </div>
  <div>
    <button id="btnExport">Export to excel</button>
  </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

这是最好的方法。您也可以指定文件名进行下载。只需将tableid,工作表名称,文件名传递给下面的函数,它将下载。有关在IE中下载的信息,请参见小提琴。

https://jsfiddle.net/ndncll/ehnbxo1u/

function tableToExcel(table, sheetName, fileName) {
fileName = fileName + new Date().formatDateTime('MM_DD_YYYY', 'HH_mm_ss');

var uri = 'data:application/vnd.ms-excel;base64,',
    templateData = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
    base64Conversion = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
    formatExcelData = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }

$("tbody > tr[data-level='0']").show();

if (!table.nodeType)
    table = document.getElementById(table)

var ctx = { worksheet: sheetName || 'Worksheet', table: table.innerHTML }

var element = document.createElement('a');
element.setAttribute('href', 'data:application/vnd.ms-excel;base64,' + base64Conversion(formatExcelData(templateData, ctx)));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);}

答案 5 :(得分:0)

非常重要,请确保列和行的宽度大于0, 尤其是当行从一个表移动到另一个表时,这成为一个问题,(当我在两个dataTables之间移动行时,我已经面对了它)

如果columns(th)或rows(td)的宽度为0,则将表下载为.xls文件,但是这些列被隐藏在excel文件中,

使用css或jquery设置宽度大于0

css

<your table> th, <your table> td {
  width:<your preference>px;
}

jquery

$("<your table> th").css("width","<your preference>px"); 
$("<your table> td").css("width","<your preference>px"); 
$("<add button>").click(function(e) {
    var a = document.createElement('a');
    var dataType = 'data:application/vnd.ms-excel';
    var getTable = document.getElementById('<add table id>');
    var readTable = getTable.outerHTML.replace(/ /g, '%20');
    a.href = dataType + ', ' + readTable;
    a.download = '<filename>.xls';
    a.click();
    e.preventDefault();
});