I have several HTML tables that I want to allow the user to export its content to a csv.
I currently have this solution implemented and it almost works perfectly:
function exportTableToCsv($table, filename) {
var $rows = $table.find('tr:has(td,th)'),
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,th');
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'
});
}
Which I call like this:
$(".ExportSummary").on('click', function () {
exportTableToCsv.apply(this, [$('#SummaryTable'), 'ExportSummary.csv']);
});
Now, my issue is that I cannot get the string formatting to work by putting the <td> in separate cells in Excel. I simply don't know how to get the text to be placed in separated cells since it is being mapped together into a whole string content.
I want the desired output that is provided with this JsFiddle - but this solution does not provide the ability to choose filename and setting the appropiate content-type (application/csv) to be recognized by the browser.
Any help is appreciated. Thanks in advance!