How to export non-text content from a Datatable

Viewed 232

I am trying to export the content of my datatable but the column status it is not being exported since it is not a text.

What I've tried so far:

LIVE DATATABLES

Basically I tried using the HTML5 export buttons plug-in like this:

dom: 'Bfrtip',
buttons: [
  'copyHtml5',
  'excelHtml5',
  'csvHtml5',
  'pdfHtml5'
]

Ideally I would like that when exporting the content, the green square is replaced by the text 'Active' and the red square by the text 'Inactive' or some other string.

2 Answers

You should refer to button.exportData() in datatables documentation.

According to the documentation, you can customize the data as you like by customizing the buttons property, which can be done like this:

var DT1 = $('#example').DataTable({ 
    ...,   
    buttons: [
        {
            extend: 'excelHtml5',
            exportOptions: {
                format: {
                     body: function (data, rowIdx, colIndex, cellNode) {
                          const statusColumn = $(cellNode).find('div')
                          if (statusColumn.length > 0) {
                             return statusColumn.is('.status-active') ? 'Active' : 'Inactive'
                          }
                          return $(cellNode).text()
                     }
                }
            },
         },
     ]
})

The above code is an example for excelHtml5 you can apply the same to buttons: copyHtml5, csvHtml5, pdfHtml5.

Full code in this link

Update:

You can use .text() method to get the combined text contents of each element in the set of matched elements, including their descendants. Like this $(cellNode).text()

Please open this working codpen click here

$(document).ready(function() {
var buttonCommon = {
    exportOptions: {
        format: {
            body: function ( data, row, column, node ) {
                // Strip $ from salary column to make it numeric
              if(column === 2){
            
                var txt = $(node).html();
               
                if(txt.indexOf("status-active") > 0){
                     data = 'Active';
                }
              if(txt.indexOf("status-inactive") > 0){
                  data = 'In Active';
                }
                
                
              }
              
                return data;
              
            }
        }
    }
};

$('#example').DataTable( {
            columns: [
        { data: 'name' },
        { data: 'position' },
        { data: 'office' },
        { data: 'age' },
        { data: 'start_date' },
        { data: 'salary' }
    ],
    dom: 'Bfrtip',
    buttons: [
        
        $.extend( true, {}, buttonCommon, {
            extend: 'excelHtml5'
        } ),
        
    ]
} );

} );

Related