Skip to content

Instantly share code, notes, and snippets.

@chocolatkey
Created January 21, 2016 18:08
Show Gist options
  • Save chocolatkey/dd15190bb3cbb80efc98 to your computer and use it in GitHub Desktop.
Save chocolatkey/dd15190bb3cbb80efc98 to your computer and use it in GitHub Desktop.
Export CSV of table (bootstrap, checkbox/empty column safe)
//Original function: https://jsfiddle.net/terryyounghk/kpegu/
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'), //Put tr:has(input:checkbox:checked) for ones with checked checkboxes
// 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');
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.replace(/"",/g, '').replace(/""/g, '').replace(/(\r\n|\n|\r)/m,"")); //Get rid of useless stuff for sure
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// CSV export on button click
$("#BUTTON").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#TABLE'), 'FILENAME.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment