$(document).ready(function() {
$('#example').dataTable();
$('<div />').css({'float' : 'left'}).css({'padding-right' : '20px'}).attr({'id' : 'fButtons'}).prependTo($('#example_wrapper'));
$('<button />').attr({
'id' : 'tabletocsv'
})
.html('CSV')
.appendTo($('#fButtons'));
$('#tabletocsv').click( function () {
rgDataTable2CSV(0);
});
function rgDataTable2CSV(mOffset) {
function row2CSV(tmpRow) {
var tmp = tmpRow.join(''); // to remove any blank rows
if (tmpRow.length > 0 && tmp !== '') {
var mystr = tmpRow.join(',');
csvData[csvData.length] = mystr;
}
}
function formatData(input) {
// replace " with “
var regexp = new RegExp(/["]/g);
var output = input.replace(regexp, "“");
//HTML
regexp = new RegExp(/\<[^\<]+\>/g);
output = output.replace(regexp, "");
if (output === "") return '';
return '"' + output + '"';
}
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600,menubar=1,resizable=1');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
generator.focus();
}
var csvData = [];
var tmpRow = [];
//get the header
var el = $('#example').find('thead');
(el).find('tr').each (function() {
tmpRow = [];
$(this).find('th').each(function(index, domEle) {
tmpRow[tmpRow.length] = formatData($.trim($(this).html()));
});
row2CSV(tmpRow); });
//get the data
$('#example').find('tr').each (function() {
tmpRow = [];
$(this).find('td').each(function(index, domEle) {
tmpRow[tmpRow.length] = formatData($.trim($(this).html()));
});
row2CSV(tmpRow); });
var mydata = csvData.join('\n');
return popup(mydata);
}
});
You can test it out here.
No comments:
Post a Comment
Thank you for commenting!