|
//http://stackoverflow.com/a/1496863 |
|
function replaceNbsps(str) { |
|
var re = new RegExp(String.fromCharCode(160), "g"); |
|
return str.replace(re, " "); |
|
} |
|
|
|
//http://jsfiddle.net/terryyounghk/KPEGU/ |
|
function _rows2csv($rows) { |
|
// Temporary delimiter characters unlikely to be typed by keyboard |
|
// This is to avoid accidentally splitting the actual contents |
|
var tmpColDelim = String.fromCharCode(11); // vertical tab character |
|
var tmpRowDelim = String.fromCharCode(0); // null character |
|
// actual delimiter characters for CSV format |
|
var colDelim = '","'; |
|
var rowDelim = '"\r\n"'; |
|
return '"' + $rows.map(function (i, row) { |
|
var $row = $(row); |
|
var $cols = $row.find('td,th'); |
|
return $cols.map(function (j, col) { |
|
var $col = $(col); |
|
var text = $col.text(); |
|
var a = text.replace('"', '""'); |
|
// escape double quotes |
|
return replaceNbsps(a); |
|
}).get().join(tmpColDelim); |
|
}).get().join(tmpRowDelim) |
|
.split(tmpRowDelim).join(rowDelim) |
|
.split(tmpColDelim).join(colDelim) + '"\r\n'; |
|
} |
|
|
|
function exportTableToCSV($table, filename) { |
|
var $bodyrows = $table.find('tr:has(td)'); |
|
var $headrows = $table.find('tr:has(th)'); |
|
|
|
// Grab text from table into CSV formatted string |
|
var csv = _rows2csv($headrows); |
|
csv += _rows2csv($bodyrows); |
|
// Data URI |
|
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv); |
|
$(this).attr({ |
|
'download': filename, |
|
'href': csvData, |
|
'target': '_blank' |
|
}); |
|
} |
The code is not working, i have tried over and over, its not working