Created
March 27, 2017 05:46
-
-
Save bobbiejwilson/5b0461e80b825f288cda994bd36d9bad to your computer and use it in GitHub Desktop.
HTML to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
function exportTableToCSV($table, filename) { | |
var $rows = $table.find('tr:has(th), tr:has(td)'), | |
// 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('th, 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); | |
$(this) | |
.attr({ | |
'download': filename, | |
'href': csvData, | |
'target': '_blank' | |
}); | |
} | |
// This must be a hyperlink | |
$(".export").on('click', function (event) { | |
// CSV | |
exportTableToCSV.apply(this, [$('#epa_view'), 'export' + Date.now() + '.csv']); | |
// IF CSV, don't do event.preventDefault() or return false | |
// We actually need this to be a typical hyperlink | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment