TableSorter : how to export results to csv?

人盡茶涼 提交于 2019-12-30 07:09:10

问题


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


回答1:


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).



来源:https://stackoverflow.com/questions/23295723/tablesorter-how-to-export-results-to-csv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!