0

I have the fiddle, modified from another forum that exports an html table to CSV with jQuery. This works perfectly however I cannot get it to include the table header rows.

The fiddle is at: http://jsfiddle.net/KPEGU/480/

I have messed around with the below syntax without any luck:

var $rows = $table.find('tr:has(td)'),

is it something to do with:

$cols = $row.find('td');

So I am looking for output to include headings, not just normal table rows.

complete script is:

$(document).ready(function () {

    function exportTableToCSV($table, filename) {

        var $rows = $table.find('tr:has(td)'),


            tmpColDelim = String.fromCharCode(11), 
            tmpRowDelim = String.fromCharCode(0), 
            colDelim = '","',
            rowDelim = '"\r\n"',

            csv = '"' + $rows.map(function (i, row) {
                var $row = $(row),
                    $cols = $row.find('td');

                return $cols.map(function (j, col) {
                    var $col = $(col),
                        text = $col.text();

                    return text.replace('"', '""'); 
                }).get().join(tmpColDelim);

            }).get().join(tmpRowDelim)
                .split(tmpRowDelim).join(rowDelim)
                .split(tmpColDelim).join(colDelim) + '"',

            // Data URI
            csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

        $(this)
            .attr({
            'download': filename,
                'href': csvData,
                'target': '_blank'
        });
    }


    $(".export").on('click', function (event) {
        // CSV
        exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);

    });
});

1 Answer 1

1

A couple small changes:

var $rows = $table.find('tr:has(td,th)'),

and

$cols = $row.find('td,th');
Sign up to request clarification or add additional context in comments.

2 Comments

champion thank you. I was trying tr:has(td), tr:has(th). Thanks again, appreciated.
Yup that worked - I am using it in my project now jsfiddle.net/KPEGU/2960 <<-- working copy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.