我正在尝试使用单个 DataTable 初始化代码块来初始化不同的表,在该代码块中我创建了 Datatable Excel 按钮来导出数据。我取得了很大的成功。但现在的挑战是我无法以正确的文件名导出数据。
实际上,当数据表初始化时,导出按钮会自动与表绑定,数据是否正确导出,但在分配文件名时,我试图通过按类搜索来获取可见的 Datatable 实例。当页面中只有一个表格时,我可以获得正确的表格。但是当单页上有多个表格时,优化可见表格不会给出正确的表格。如何在我的 JS 代码中获得正确的表实例,以便它在正确的表上完全工作。
这就是我试图获取可见数据表的方式$('.dt-table:visible').data('excel-filename')
请让我知道如何使用以下代码获得更具体的表格。
JS代码
var tableObj = $('.dt-table').DataTable({
retrieve: true,
"lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, 'All'] ],
"language": {
"emptyTable": "No data available to show...",
"info": "Showing _START_ to _END_ from _TOTAL_ records",
"infoEmpty": "0 records to show...",
"lengthMenu": "Show _MENU_ records",
"loadingRecords": "Loading...",
"processing": "Processing...",
"zeroRecords": "No matching records found...",
"infoFiltered": "(filtered from _MAX_ total records)"
},
dom: "<'row'<'col-sm-12'B>>" +
"<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: {
buttons: [
{
text: '<i class="far fa-file-excel pr-2"></i> Export to Excel(.xlsx)',
title: function(thead, data, start, end, display) {
return $('.dt-table:visible').data('excel-title');
},
extend: 'excel',
autoFilter: true,
filename: function() {
var d = new Date($.now());
var n = d.getDate()+"_"+(d.getMonth()+1)+"_"+d.getFullYear()+"_"+d.getHours()+"_"+d.getMinutes()+"_"+d.getSeconds();
return $('.dt-table:visible').data('excel-filename') + '_' + n;
},
customize: function(xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$( 'sheets sheet', xlsx.xl['workbook.xml'] ).attr( 'name', $('.dt-table:visible').data('excel-title') );
},
exportOptions: {
//columns: [ 1, 2, 3 ]
format: {
body: function (data, row, column, node) {
if($(node).find(".notExportable").length) {
return $(data).remove(".notExportable").html();
} else {
return data;
}
}
},
columns: ':not(.notExportable)'
}
}
],
dom: {
container: {
tag: "div",
className: "mb-2 mlmt-act dt-buttons"
},
button: {
tag: "a",
className: "btn btn-info mlmt-button"
},
buttonLiner: {
tag: null
}
}
},
drawCallback: function() {
var hasRows = this.api().rows({ filter: 'applied' }).data().length > 0;
var tableId = this.api().tables().nodes().to$().attr('id');
var excelButton = $('a.mlmt-button[aria-controls="'+tableId+'"]');
//alert(tableId);
//alert('.mlmt-button-'+($('.dt-table:visible').attr('id')));
if(hasRows > 0) {
excelButton.removeAttr('style');
} else {
excelButton.css('pointer-events', 'none').css('background-color', 'gray');
}
}
});
代码
<table class="table table-bordered table-hover table-striped dt-table" id="tblAllLic" data-page-length='10' data-order='[[0, "asc"]]' data-excel-title="All License List" data-excel-filename="All_Licenses">
</table>