(一)代码示例
html代码和javascript代码可以参考官网的例子:https://datatables.net/extensions/buttons/examples/initialisation/simple.html。
(二)DataTables配置
需要用到jQuery和DataTables相关的css和javascript代码:
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<link href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css" rel="stylesheet">
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
试了一下发现导出按键并没有显示:
注意官方示例下说明了需要使用以下javascript脚本:
再对比javascript - Bootstrap 示例中未显示数据表按钮加上dataTables.buttons.min.js
可以使用按键的尺寸更加合适。最后的要使用的javascript脚本为:
<head>
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<link href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
<script src="http://cdn.datatables.net/buttons/2.0.1/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.print.min.js"></script>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
dom: 'lBfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
} );
} );
</script>
</head>
正常效果:
默认情况下导出的是全表,即示例中所有57条数据。但是如果数据是从服务器获取的,因为前端只有当前页的数据,那么导出的数据也只有当前页而非全表。
(三)数据来源为服务端时如何实现导全表
其实可以将需求拆分为2步:(1) 从服务器取得全部数据。(2) 导出表格。这样便可以达到曲线救国的效果。
导出按键的代码为:
$(document).ready(function() {
var table = $('#example').DataTable( {
dom: 'lBfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print',
{
text: "Export",
action: function ( e, dt, node, config ) {
select = $("#example_length").children().children();
select.val(100);
select.trigger("change");
setTimeout(function(){
excel = $("#example_length").next().children()[2];
excel.click();
}, 1000);
}
},
],
} );
} );