TableSorter : how to export results to csv?

后端 未结 1 825
猫巷女王i
猫巷女王i 2021-01-06 16:47

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 co

相关标签:
1条回答
  • 2021-01-06 17:52

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

    0 讨论(0)
提交回复
热议问题