Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Datatable csv button from custom button

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

like image 628
MPPNBD Avatar asked Aug 04 '17 21:08

MPPNBD


2 Answers

At last i found the solution.

In Datatable configuration , i added click event for the button to be triggered.

buttons: [
        { 
            extend: 'csv',
        }
    ]

$("#ExportReporttoExcel").on("click", function() {
    table.button( '.buttons-csv' ).trigger();
});

This works fine for me thanks for the comments and answers

like image 57
MPPNBD Avatar answered Oct 26 '22 13:10

MPPNBD


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.

like image 33
Hayat Tuge Avatar answered Oct 26 '22 13:10

Hayat Tuge