chntgomez
chntgomez

Reputation: 2119

Custom value for export CSV in DataTables (jQuery)

I am using a custom function to render an HTML icon in a DataTable column instead of showing plain text:

    {data: {newCost : "newCost", oldCost:"oldCost"},
            title: "Difference",
            render:  {"display":function(data) {

                    if (parseFloat(data.newCost) > parseFloat(data.oldCost)) {
                        return '<i class="fas fa-arrow-up icon-red" data-sort="1" style="margin-left: 4px"></i>'
                    }
                    if (parseFloat(data.newCost) === parseFloat(data.oldCost)) {
                        return '<i class="fas fa-equals" data-sort="0" style="margin-left: 4px"></i>'
                    } else {
                        return '<i class="fas fa-arrow-down icon-green" data-sort="-1" style="margin-left: 4px"></i>'
                    }
                }, "sort": function(data){
                    return data.newCost - data.oldCost;
                }, "_":function(data){
                    return data.newCost - data.oldCost;
                }
            }
        },

enter image description here

As you can see, I am using a render function to display an arrow given the difference between the 2 values of oldCost and newCost. But when I export this using the export buttons plugin, the Column shows a blank space. I would like to show the plain text value of the difference.

Is that possible?

Upvotes: 2

Views: 1518

Answers (1)

davidkonrad
davidkonrad

Reputation: 85518

You could store the difference as an attribute:

render: {"display":function(data) {
  var difference = data.newCost - data.oldCost;
  if (parseFloat(data.newCost) > parseFloat(data.oldCost)) {
      return '<i data-value="'+difference+'" class="fas fa-arrow-up icon-red" data-sort="1" style="margin-left: 4px"></i>'
  }
  ...

In return that attribute value in export options:

{
  extend: 'csvHtml5',
  exportOptions: {
    format: {
      body: function(data, row, column, node) {
        if (column == 42) { //dont know the index
          return $(data).attr('data-value')
        }
      }
    }    
  }    
}

To clarify: The blank space appears because the text value of the <i> elements is ''.

Upvotes: 2

Related Questions