Export selected rows with buttons collection not w

2019-06-04 18:47发布

问题:

I am trying to export only the selected rows from a dataTable. I could successfully export selected rows to a csv file by setting extend option to csv as shown in the below code.

buttons: [
    'colvis',
    'selectAll',
    'selectNone',
    {
        extend: 'csv',
        text: 'Export Selected',
        exportOptions: {
            columns: ':visible:not(.not-exported)',
            modifier: {
                 selected: true
            }
        },
        title: 'Data export'
    }
],

But I want to have a drop down(csv, copy, print) from which I can choose to export the selcted rows to. I tried using collection as in the below code. But it exports all the visible rows. Someone pls help

buttons: [
    'colvis',
    'selectAll',
    'selectNone',
    {
        extend: 'collection',
        text: 'Export Selected',
        buttons: ['copy','csv','print'],
        exportOptions: {
            columns: ':visible:not(.not-exported)',
            modifier: {
                 selected: true
            }
        },
        title: 'Data export'
    }
],

回答1:

You define "selected only" simply by using rows: '.selected'. However: Even though you are using a collection, you will still need to provide settings for each button. I.e

buttons: ['copy','csv','print'],

should be

buttons: [
  { extend :'copy',
    exportOptions : {
     columns: ':visible:not(.not-exported)',
     rows: '.selected'
  }
  ...
]

You can reduce the amount of code by reusing a simple literal

var exportOptions = {
  columns: ':visible:not(.not-exported)',
  rows: '.selected'
}

The working sample code will end up like this :

buttons: [
  'colvis',
  'selectAll',
  'selectNone',
  {
    extend: 'collection',
    text: 'Export Selected',
    buttons: [
      { extend : 'copy',
        exportOptions: exportOptions
      },
      { extend : 'csv',
        exportOptions: exportOptions
      },
      { extend : 'print',
        exportOptions: exportOptions
      }
    ]   
  }
]

here is a demo -> https://jsfiddle.net/youn7zm4/