Reputation: 10809
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']);
});
});
Upvotes: 0
Views: 1511
Reputation: 2182
A couple small changes:
var $rows = $table.find('tr:has(td,th)'),
and
$cols = $row.find('td,th');
Upvotes: 1