【问题标题】:Export HTML table to Excel file将 HTML 表格导出到 Excel 文件
【发布时间】:2016-01-22 23:36:33
【问题描述】:

我一直在研究一些能够做到这一点的 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(){}) 块内,什么也没发生。

【问题讨论】:

  • 浏览器控制台是否显示错误?
  • 不,什么都没有。
  • 当它应该在里面时,它肯定在就绪块之外。在单击处理程序中放置警报或控制台登录以查看它是否正在触发

标签: javascript jquery html excel


【解决方案1】:

这是您能做的最好的方法。您也可以指定文件名进行下载。只需将 tableid、工作表名称、文件名传递给下面的函数,它就会下载。也可以在 IE 中查看 fiddle。

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);}

【讨论】:

    【解决方案2】:

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

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

    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/

    【讨论】:

    • 这个方法只适用于firefox和chrome浏览器吗?我在 IE9 中尝试过,它不起作用,单击按钮时显示 webpage cannot be displayed 错误。你能帮忙吗?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      设法修复它。我最初怀疑不把它放在 ready 函数中会是一个问题,并认为它会解决这个问题,但这只是问题的一部分。我也忘记了一个逗号。完成的结果如下。

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

      【讨论】:

        【解决方案5】:

        这是您可用于将 HTML 表格导出到具有自定义文件名的 excel 文件的代码。我试过 IE11 、 Firefox 48 和 chrome 51 。

        1. 在 HTML 部分添加&lt;iframe id="txtArea1" style="display:none"&gt;&lt;/iframe&gt;。
        2. 添加一个按钮&lt;button id="btnExport" onclick="toExcel_()"&gt;Export to excel&lt;/button&gt;,它将调用函数“toExcel_()”。

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

        }

        【讨论】:

          【解决方案6】:

          非常重要,请确保列和行的宽度大于 0, 这成为一个问题,尤其是当行从一个表移动到另一个表时,(我在两个数据表之间移动行时遇到过)

          如果 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();
          });
          
          

          【讨论】:

            猜你喜欢
            • 2014-10-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-06
            • 2016-05-15
            • 2018-06-24
            • 2023-03-21
            • 2014-04-08
            相关资源
            最近更新 更多