How to call Datatable csv button from custom button

Viewed 26705

Need to call csv button from my custom button.

<button value="Export report to Excel" class="button-default datatable-csv" type="button" id="ExportReporttoExcel">
                <span>Export report to Excel</span>
            </button>

Instead of calling it from the Datatable button, i want the same functionality from the above button.

Looking for some configuration changes in Datatable so that i can call my custom button to export the table records as csv.

var table=$('#tableId').DataTable( {
    "paging":   true,
    "info":     true,
    "searching": true,      
    ,buttons: true
});


$("#SEARCH").on("keyup search input paste cut", function() {
    table.search(this.value).draw();
});

var buttons = new $.fn.dataTable.Buttons(table, {
     buttons: [
       'csvHtml5'
    ]
}).container().appendTo($('#ExportReporttoExcel'));

Getting output like below but i need only one button.

enter image description here

4 Answers

Say you have your own button

<a href="javascript:;" style="some button style" class="button_export_excel">Export Excel</a>

And you have your table that you are using the below code for;

$(document).ready(function () {
    var table = $('#example').DataTable({
        "paging": false,
        "info": false,
        searching: false,
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excelHtml5'
            }
        ]
    });
});

Then all you need to do is to use this code below:

$('#example').DataTable({
        "paging": false,
        "info": false,
        buttons: [
            {
                extend: 'excel'
            },
            {
                extend: 'csv'
            },
        ]
    });
$('.button_export_excel').click(() => {
    $('#example').DataTable().buttons(0,0).trigger()
})

The 0,0 points to excel and if you want to point to csv you do 0,1.

Related