Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all articles
Browse latest Browse all 82006

Simple CSV Export with jQuery & PHP

$
0
0
Hello,

after trying out TableTools (despite hating Flash) which didn't really work for me, I wrote a simple and fast CSV export function in jQuery which I wanted to share here. Hope this may be helpful to some of you. I am sure one can still do this better than I did, please do not hesitate to comment :)

Here ist the function :
function table2csv(oTable, exportmode, tableElm) {
        var csv = '';
        var headers = [];
        var rows = [];

        // Get header names
        $(tableElm+' thead').find('th').each(function() {
            var $th = $(this);
            var text = $th.text();
            var header = '"' + text + '"';
            // headers.push(header); // original code
            if(text != "") headers.push(header); // actually datatables seems to copy my original headers so there ist an amount of TH cells which are empty
        });
        csv += headers.join(',') + "\n";

        // get table data
        if (exportmode == "full") { // total data
            var total = oTable.fnSettings().fnRecordsTotal()
            for(i = 0; i < total; i++) {
                var row = oTable.fnGetData(i);
                row = strip_tags(row);
                rows.push(row);
            }
        } else { // visible rows only
            $(tableElm+' tbody tr:visible').each(function(index) {
                var row = oTable.fnGetData(this);
                row = strip_tags(row);
                rows.push(row);
            })
        }
        csv += rows.join("\n");

        // if a csv div is already open, delete it
        if($('.csv-data').length) $('.csv-data').remove();
        // open a div with a download link
        $('body').append('<div class="csv-data"><form enctype="multipart/form-data" method="post" action="/csv.php"><textarea class="form" name="csv">'+csv+'</textarea><input type="submit" class="submit" value="Download as file" /></form></div>');

}

function strip_tags(html) {
    var tmp = document.createElement("div");
    tmp.innerHTML = html;
    return tmp.textContent||tmp.innerText;
}


This creates a textarea with the code to be copy pasted manually and a button to download a csv-file.
My table is a table with the class "display". So here are my two export buttons :

    
// export only what is visible right now (filters & paginationapplied)
$('#export_visible').click(function(event) {
        event.preventDefault();
        table2csv(oTable, 'visible', 'table.display');
    })

// export all table data
$('#export_all').click(function(event) {
        event.preventDefault();
        table2csv(oTable, 'full', 'table.display');
    })
I call these in the same init file where I also set up the dataTable (otherwise I wouldn't have access to the variable).
This is the way I set up my datatable :
$(document).ready(function(){
   var asInitVals = new Array();
    var oTable = $('table.display').dataTable();
});

And the PHP file csv.php at the website root to generate a downloadable CSV :
<?
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="tabledata.csv"');
if (isset($_POST['csv'])) {
    $csv = $_POST['csv']; 
    echo $csv;
}
?>

The export works also with FixedColumns.

Thank you Allan for your great work and documentation.

Best regards.

Viewing all articles
Browse latest Browse all 82006

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>