I wanted to reverse column on export data from DataTables. I look for method to do it and finally ended up with this way:
$(document).ready(function(){
var arrayCol = new Array();
var table = $('#example').DataTable({
dom: 'Bfrtip',
initComplete:function ( ) {
var len = this.api().columns().count();
var array = Array.from(Array(len).keys())
arrayCol = array.reverse();
},
buttons: [
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible:not(.not-export-col)',
orthogonal: 'export'
}
},
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4',
exportOptions: {
columns: arrayCol, // this doesn't work
//columns:[5,4,3,2,1,0], //this work
orthogonal: 'export'
}
}
]
});
});
The var arrayCol when debugging has values but when exporting to PDF the PDF doesn't have any columns.
Maybe it doesn't assign to columns or something like that.
I think the simplest way is to reverse each individual row array, as you are exporting the data. You can use exportOptions.rows to do this.
You also need to reverse the headers, which can be done using exportOptions.format.heeader. In this case, you only get access to one header field at a time, so there is a bit more work needed to build a reversed array of header values and then access each index location in that array:
$(document).ready(function() {
var table = $('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'pdf',
text: 'To PDF',
exportOptions: {
rows: function ( idx, data, node ) {
return data.reverse();
},
format: {
header: function ( data, idx, node ) {
var headers = $('#example').DataTable().table().header();
var reversedHeaders = headers.innerText.split('\t').reverse();
return reversedHeaders[idx];
}
}
}
}
]
} );
} );
References: