将 Bootstrap 数据 table 的所有行导出到 Excel

Export Bootstrap Data table's all rows to Excel

我在将 Bootstrap 数据 Table 行导出到 Excel 时遇到问题。

为了将数据导出到 Excel,我正在使用一个名为 jquery.table2excel.js 的外部插件。

导出数据table到excel的代码如下:

<script type="text/javascript" src="js/jquery.table2excel.js">
</script>
<script>
 $(function() {
    var startDate = $(".startDate").val();
    var endDate = $(".endDate").val();
    $("#exportExcel").click(function(){
        $("#table_id").table2excel({
            exclude: ".noExl",
            //name: "Excel Document Name",
            filename:  "Data from " + startDate + " to " + endDate
        }); 
     });
    $("#table_id").dataTable();
  });
</script>

对于数据table 我正在使用以下库:

<script type="text/javascript" src="js/jquery.dataTables.min.js">
</script>
<script type="text/javascript" src="js/dataTables.bootstrap.js">
</script>

Table如下:

<table id="table_id" class="table table-striped table-condensed table-
bordered">
  <thead>`Table Headers here`</thead>
  <tbody>`Rows from Database here`</tbody>
</table>

问题描述如下:

  1. 当我尝试使用导出功能时,只有可见行被导出到 excel 而不是分页行。

例如假设如果我每页有 10 行,那么只会导出前 10 行,当我将每页行更改为 25 行时,将导出所有 25 行。

我希望使用我正在使用的插件一次导出所有行。有什么想法吗?

解决方案

您可以使用 $() 方法访问所有行,甚至不存在于 DOM 中,并使用这些行构建一个新的 table。然后你可以在新构建的 table 上执行 table2excel() 以获得包含所有行的 Excel 文件。

例如:

$(function() {
   var startDate = $(".startDate").val();
   var endDate = $(".endDate").val();

   $("#exportExcel").click(function(){
      $('<table>')
         .append(
            $("#table_id").DataTable().$('tr').clone()
         )
         .table2excel({
            exclude: ".excludeThisClass",
            name: "Worksheet Name",
            filename: "SomeFile" //do not include extension
         });
   });

   $("#table_id").dataTable();
});

演示

有关代码和演示,请参阅 this page

注意事项

Excel 2013打开table2excel.js.

生成的文件时显示如下错误

Excel cannot open the file [filename] because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

由于这个错误,我宁愿使用 DataTables TableTools plug-in 而不是它,即使它只能生成 CSV 文件并且还使用 Flash。

我找到解决方案 here 将数据从 table 导出到 excel sheet