CSV Export with jQuery for 1.10.0-dev version

CSV Export with jQuery for 1.10.0-dev version

pioneer903pioneer903 Posts: 4Questions: 3Answers: 0
edited December 2014 in Free community support

I was looking for a way to export data to CSV file and found the discussion [Simple CSV Export with jQuery] (http://datatables.net/forums/discussion/11984/simple-csv-export-with-jquery-php) posted by @ulrike.

It did not work for me for the following reasons:
1. It used an older version of DataTables
2. I did not want to export hidden columns.
3. <? ?> tags were missing php

So here is my modification of @ulrike 's code:
HTML:

<a id="export_visible" class="btn btn-success">Export Visible</
<a id="export_all" class="btn btn-success">Export All</a>

JavaScript

$(document).ready(function(){
var asInitVals = new Array();
            var oTable = $('table.dataTables-reports').DataTable();


            // export only what is visible right now (filters & paginationapplied)
            $('#export_visible').click(function(event) {
                    event.preventDefault();
                    table2csv(oTable, 'visible', 'table.dataTables-reports');
                });
             
            // export all table data
            $('#export_all').click(function(event) {
                    event.preventDefault();
                    table2csv(oTable, 'full', 'table.dataTables-reports');
                });
            
            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 totalRows = oTable.data().length;
                        for(i = 0; i < totalRows; i++) {
                            var row = oTable.row(i).data();
                            console.log(row)
                            row = strip_tags(row);
                            rows.push(row);
                        }
                    } else { // visible rows only
                        $(tableElm+' tbody tr:visible').each(function(index) {
                            var row = [];
                            $(this).find('td').each(function(){
                                var $td = $(this);
                                var text = $td.text();
                                var cell = '"' +text+ '"';
                                row.push(cell);
                            });
                            rows.push(row);
                        })
                    }
                    csv += rows.join("\n");
                    
                    $('body').append('<div class="csv-data hidden"><form enctype="multipart/form-data" method="post" action="csv.php"><textarea class="form" name="csv">'+csv+'</textarea></form></div>');
                    $('.csv-data form').submit();
             
            }
             
            function strip_tags(html) {
                var tmp = document.createElement("div");
                tmp.innerHTML = html;
                return tmp.textContent||tmp.innerText;
            }
});

PHP
```php
<?php
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=tabledata.csv');
if (isset($_POST['csv'])) {
$csv = $_POST['csv'];
echo $csv;
}

<?php > ``` ?>

Hope this will save somebody time.

P.S. I also found another example that may work for you: http://jsfiddle.net/santeriv/qtQPf/

Replies

  • allanallan Posts: 63,532Questions: 1Answers: 10,475 Site admin

    Hi,

    Thanks for posting this! I'm sure others will find it useful.

    Regards,
    Allan

This discussion has been closed.