Skip to content

Instantly share code, notes, and snippets.

@octoxan
Created September 2, 2016 13:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save octoxan/93c1efb765c3a3bfca6a0022bcbafda7 to your computer and use it in GitHub Desktop.
Save octoxan/93c1efb765c3a3bfca6a0022bcbafda7 to your computer and use it in GitHub Desktop.
Export HTML Table as CSV
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td),tr:has(th)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
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(/"/g, '""'); // escape double quotes
}).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);
if (window.navigator.msSaveBlob) { // IE 10+
//alert('IE' + csv);
window.navigator.msSaveOrOpenBlob(new Blob([csv], {
type: "text/plain;charset=utf-8;"
}), "csvname.csv")
} else {
$(this).attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
}
// button has to be an anchor, don't use prevent default because it
// actually has to link to the generated csv
$("#anchor").on('click', function() {
exportTableToCSV.apply(this, [$('table'), 'export.csv']);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment