Setting up a custom file name datatables export ex

2020-02-13 01:23发布

问题:

I'm wondering how to set a custom filename to export in datatables buttons excelHtml5 with a select, I did a function to pass the name but is not setting it ill post my js code. with the alert it is reflecting the changes but when i call the excel button in datatables is coming empty.

Here is the code:

var reportName = '24 afterhours ';
$('#example').DataTable({
   dom: 'Bfrtip',
   buttons: [
      {
         extend: 'excelHtml5',
         title: reportName
      },
      {
         extend: 'pdfHtml5',
         title: 'Data export'
      }
  ]
});

$('#campaing').change(function() {
   reportName += $(this).find(":selected").text() + ' report';
});

I think I might be missing something.

回答1:

title is read once when the dataTable is initialised, and then the value is mapped into the internal config object. Therefore, if you want to change settings dynamically, you must change that internal config object, not try to change the readonly configuration settings.

So do it the other way around - create an event listener for the <select> inside the buttons init() callback itself. If you have a <select> with optional filenames like this

<select id="filename">
    <option value="filenameA">filename A</option>
    <option value="filenameB">filename B</option>
    <option value="filenameC">filename C</option>
</select>

Then you can dynamically change the export fileName (== title + extension) by

buttons : [
   {
    extend: 'excelHtml5',
    title: 'filenameA', //default filename
    init: function(dt, node, config) {
        $("#filename").on('change', function() {
            config.title = this.value;
        })
    }
},

You can change the other config properties from within the handler as well, for example you might want change config.extension to something else.


Here is a demo -> https://jsfiddle.net/y8d9zhfv/ It is important to emphasize, that dataTables.buttons.js 1.3.0 or higher is required; this is also the case with the buttons.html5.js module. So if the above not work upgrade -> https://cdn.datatables.net/buttons/



回答2:

You can also use the filename config object to set it. I have used this method for my export files and it works with earlier versions of dataTables.buttons.js as I am using it with v1.2.1, I am using it like so:

buttons: [
             {
                 extend: 'excel',
                 filename: function(){
                     return reportName;
                 }
             }
         ]

Where reportName is a variable I am setting when input options are changing.