Get Dynamic Filename and Title for Export button in Datatable

1.5k Views Asked by At

I am trying to init different tables with single DataTable initialization code block in which I have created Datatable Excel Button to export data. and I got success pretty much. But now challenge is that I am not able to export data with correct file name.

Actually when datatable initialized, Export button is automatically bind with the table do data is being exported correctly but while assigning file name I am trying to get visible Datatable instance by searching by its class. I am able to get correct table when there is only one table in the page. but when there are multiple table on single page then fining visible table does not give correct table. How can I get correct table instance in my JS code so that it works exactly on correct table.

This is how I am trying to get my visible datatable $('.dt-table:visible').data('excel-filename')

Please let me know how can I get more specific table using below code.

JS CODE

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

HTML CODE

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

There are 0 best solutions below