1

Can anybody tell me how to export Backgrid.js table data as csv when clicking on a button. I have shown a table using backgrid.js.Now I want to export the data as csv file.

arupnathdaw
  • 293
  • 1
  • 2
  • 8

1 Answers1

1

You can try something like this with underscore.js:

// columnsParam -> columns parameter you passed when created backgrid
// collection -> collection you passed when created backgrid

var columns = _.indexBy(columnsParam, 'name'),
    labels = _.pluck(columnsParam, 'label'),
    keys = _.pluck(columnsParam, 'name');

var csv = labels.join(',') + '\n';

csv += collection.map(function(item) {

    return _.map(keys, function(key) {
        var cell = columns [key].cell,
            // suppose you want to preserve custom formatters
            formatter = cell.prototype && cell.prototype.formatter;

        return formatter && formatter.fromRaw ?
            formatter.fromRaw(item.get(key), item) : item.get(key);
    }).join(',');

}).join('\n');

It's not perfect (doesn't deal with usual formatters), but demonstrates the idea.

update

To download csv as a file, you can bind a handler to your button:

var encodedUri = encodeURI('data:text/csv;charset=utf-8,' + csv),
var link = document.createElement('a');
link.setAttribute('href', encodedUri);
link.setAttribute('download', 'data.csv');

link.click();
slopen
  • 421
  • 5
  • 7