Exclude columns from export based on number of columns
Exclude columns from export based on number of columns
I have searched for the answer to this question, but I haven't found it. I have a table that works well in a browser. It is a list of products for a company, but if the company has multiple brands, I add in a brand column, and if the data covers more than the current day, I add in a date column.
When I export to Excel, though, the table has a number of links, which I want to exclude from the export. These are always the last three columns, but because of the possible addition of a date or brand column these might (for example) be 3, 4, and 5 or 4, 5, and 6. I can get the index of the last column with var indexLastColumn = $(".datatable").find('tr')[0].cells.length - 1;
I would like to set the columns to export for Excel in exportOptions to be based on how many columns I have so that in my first example I would have columns: [0, 1, 2]
and in my second I would have columns: [0, 1, 2, 3]
. My jQuery/JavaScript is not very good, but I was hoping to be able to do something like this:
$(document).ready(function() {
var indexLastColumn = $(".datatable").find('tr')[0].cells.length - 1;
/* alert (indexLastColumn); works correctly here */
$.fn.dataTable.moment( 'MMM D, YYYY' );
$('.datatable').DataTable( {
dom: 'Blfrtip',
buttons: [
'copy', 'csv', 'print',
{
extend: 'excel',
title: 'some title',
messageTop: 'Links only available online.',
exportOptions: { /* columns: [0, 1, 2] here without any if works fine */
if (indexLastColumn === 5) {
columns: [0, 1, 2]
}
else { /* (indexLastColumn === 6) { a couple of else ifs to handle a date column needed... */
columns: [0, 1, 2, 3]
}
}
}
]
} );
} );
Everything in this works properly except for my attempt to manipulate which columns to include in exportOptions. If someone could point me in the right direction (tell me what I'm doing wrong), I'd appreciate it.
Thanks--
Al
Answers
Take a look at this example. Its says that the
column-selector
can be used to determine the columns exported. There are some examples but the easiest might be to assign a class to the columns you want to export.Kevin
"columns" in this context can be a function:
Try your conditional statements in the function.
Thank you very much. I marked the th elements of all the columns that I wanted to show in the Excel export as
class="important"
and then in exportOptions, I didcolumns: ['.important']
. It showed just the columns that I wanted. I didn't need to worry about how many columns there wereOut of curiosity, can you exclude rather than include classes?
--Al
@alg The
column-selector
docs provide all the options with one being a jQuery selector. That should allow for the jQuery :not() selector.Kevin