jQuery export to Excel, include html th rows

谁说胖子不能爱 提交于 2019-12-08 12:46:07

问题


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:


A couple small changes:

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

and

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


来源:https://stackoverflow.com/questions/20216495/jquery-export-to-excel-include-html-th-rows

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