Export table to CSV
Export table to CSV using jQuery
by Julian Ritchey
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<table id="tableId">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
</tr>
<tr>
<td>Item 4</td>
<td>Item 5</td>
<td>Item 6</td>
</tr>
</tbody>
</table>
<input type="button" id="exportBtn" value="Export" />
<p id="response"></p>
</body>
CSS
#exportBtn {
margin-top: 12px;
}
#tableId {
border: 1px solid black;
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
}
JavaScript
var tableId = $('#tableId');
var fileName = 'yourFile';
$('#exportBtn').click(function() {
exportTableToCSV.apply(this, [tableId, fileName]);
if (saveAsAnswer == 'saved') {
$('#response').html(fileName + '.csv was successfully exported!');
} else if (saveAsAnswer == 'not saved') {
$('#response').html(fileName + '.csv was not successfully exported.');
}
})
function exportTableToCSV($table, filename, answer) {
var $rows = $table.find('tr'),
//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
var IEwindow = window.open();
IEwindow.document.write(csv);
IEwindow.document.close();
if (IEwindow.document.execCommand('SaveAs', false, filename + ".csv")) {
saveAsAnswer = 'saved';
} else {
saveAsAnswer = 'not saved';
}
IEwindow.close();
}