Stackoverflow Response: Export to CSV using jQuery and html
http://stackoverflow.com/questions/16078544/export-to-csv-using-jquery-and-html
by Terry Young
HTML
<div>
Demo for StackOverflow Answer to the question: <a href="http://stackoverflow.com/questions/16078544/export-to-csv-using-jquery-and-html" target="_blank">Export to CSV using jQuery and html</a>
</div>
<button class="export">Export Table data into Excel</button>
<div id="dvData">
<table>
<tr>
<th>Column One</th>
<th>Column Two</th>
<th>Column Three</th>
</tr>
<tr>
<td>row1 Col1</td>
<td>row1 Col2</td>
<td>row1 Col3</td>
</tr>
<tr>
<td>row2 Col1</td>
<td>row2 Col2</td>
<td>row2 Col3</td>
</tr>
<tr>
<td>row3 Col1</td>
<td>row3 Col2</td>
<td>row3 Col3</td>
</tr>
<tr>
<td>row4 'Col1'</td>
<td>row4 'Col2'</td>
<td>row4 'Col3'</td>
</tr>
<tr>
<td>row5 "Col1"</td>
<td>row5 "Col2"</td>
<td>row5 "Col3"</td>
</tr>
<tr>
<td>row6 "Col1"</td>
<td>row6 "Col2"</td>
<td>row6 "Col3"</td>
</tr>
</table>
</div>
JavaScript
$(document).ready(function() {
function exportTableToCSV($table, filename) {
var $rows = $table.find('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('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) + '"';
if (false && window.navigator.msSaveBlob) {
// Deliberate 'false', see comment below
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});
// Crashes in IE 10, IE 11 and Microsoft Edge
// See MS Edge Issue #10396033: https://goo.gl/AEiSjJ
// Hence, the deliberate 'false'
// This is here just for completeness
// Remove the 'false' at your own risk
window.navigator.msSaveBlob(blob, filename);
/*@cc_on
// IE9 executes this Conditional Compilation
} else if ('ActiveXObject' in window) {
// For IE9, create a hidden iframe,
// write the CSV into the iframe, then use
// execCommand to save the contents
var $iframe = $('#csvDownloadFrame');
if (!$iframe.length) {
$iframe = $('<iframe>', {
id: 'csvDownloadFrame',
sandbox: "allow-forms allow-scripts",
seamless: "seamless"
})
...