Datatables TableTools - Is it possible to only include the visible columns when saving CSV?

StackOverflow https://stackoverflow.com/questions/23484036

  •  16-07-2023
  •  | 
  •  

Question

I did some tests using the TableTools plugin for Datatables on saving CSV.

I noticed that it saves everything. It does not care if you filtered the rows nor if you hide some columns.

Is there a way to only save the data from visible columns?

Was it helpful?

Solution

You want to use the mColumns when defining your buttons.

An example from the documentation:

$(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "aButtons": [
                {
                    "sExtends": "csv",
                    "sButtonText": "Special columns",
                    "mColumns": [ 0, 1, 4 ]
                },
                {
                    "sExtends": "csv",
                    "sButtonText": "Visible columns",
                    "mColumns": "visible"
                }
            ]
        }
    } );
} );

This defines two buttons that will export to a CSV file. The first one, labeled Special columns, will only exports columns 0,1,4. The second button, labeled Visible columns will export all columns that are visible.

The mColumns parameter is described like this in the documentation:

The parameter can either be a string with a value of 'all', 'visible', 'hidden' or 'sortable' - or an array of integers with the column indexes to be exported.

This functionality is not new in the 1.10 version. It was also available in the older version, if you have no yet upgraded.

OTHER TIPS

Just for completion... on the last version of DataTables, it's slightly different (here's the documentation):

$(document).ready(function() {
  $('#example').DataTable( {
      dom: 'Bfrtip',
      buttons: [
          {
              extend: 'print',
              exportOptions: {
                  columns: ':visible'
              }
          },
          'colvis'
      ],
      columnDefs: [ {
          targets: -1,
          visible: false
      } ]
  } );
} );

Just to add a couple more options, which I needed for my scenario, which may be useful to someone.

Passing more than one parameter to columns, and using not() to exclude columns with a class:

extend: 'csv',                   
exportOptions: {
   columns: ':not(.noShow):visible'
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top