Question

TableSorter is a great jquery script to sort html tables with many options.

But I don't know how to add a simple 'export to csv' button (or link) to get a file containing the records of my table (with no special formatting).

I know the Output Plugin but it seems far too complex to me.

Thanks by advance for your help !

Ted

Was it helpful?

Solution

It's actually not complicated, it only looks intimidating because of all the options. The output widget can output csv, tsv, any other separated (space, semi-colon, etc) values, javascript array or JSON.

If you are just using basic functionality, the default settings will:

  • Output csv to a popup window
  • Only include the last header row
  • Only include filtered rows (so all rows if the filter widget isn't even being used)
  • Will only output the table cell text (ignores HTML)

All you would need is this code (demo):

HTML

<button class="download">Get CSV</button>
<table class="tablesorter">
    ....
</table>

Script

$(function () {
    var $table = $('table');

    $('.download').click(function(){
        $table.trigger('outputTable');
    });

    $table.tablesorter({
        theme: 'blue',
        widgets: ['zebra', 'output']
    });
});

I created another demo, showing all options, with a set of radio buttons which allow the user to choose between sending the output to a popup window, or downloading the file.

HTML

<label><input data-delivery="p" name="delivery" type="radio" checked /> popup</label>
<label><input data-delivery="d" name="delivery" type="radio" /> download</label>
<button class="download">Get CSV</button>

Script

var $table = $('table');

$('.download').click(function(){
    // get delivery type
    var delivery = $('input[name=delivery]:checked').attr('data-delivery');
    $table.data('tablesorter').widgetOptions.output_delivery = delivery;        
    $table.trigger('outputTable');
});

So, you can make it as simple or complex as you want (see the actual output widget demo which allows the user to set almost all the options).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top