Put this code into a script section into a common HTML head include file:
$(document).ready(function() {
$('table').each(function() {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to spreadsheet");
$button.insertAfter($table);
$button.click(function() {
var csv = $table.table2CSV({delivery:'value'});
window.location.href = 'data:text/csv;charset=UTF-8,'
+ encodeURIComponent(csv);
});
});
})
Note:
- Requires JQuery and table2CSV (i.e. put script references before the script above)
- “table” selector is a JQuery selector and can be adjusted to suit your needs
- Only works in browsers with full “Data URI” support (Firefox, Chrome, Opera) but not in IE (which only supports Date URIs for embedding binary image data into a page)
- For full browser compatibility you would have to use a slightly different approach that requires a server side script (e.g. a Java Servlet) to “echo” the CSV. Maybe I will blog about that in another post.