I am trying to refer to this code where a we are downloading a CSV file on click of a link.
$(document).ready(function () {
function exportTableToCSV($
When I tried this code, I was not able to get results in IE plus this code only iterates over td, it will skip any th present in your table. I have modified the code to resolve both the issues I was facing:
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr'),
tmpColDelim = String.fromCharCode(11),
tmpHeadDelim = String.fromCharCode(11),
tmpRowDelim = String.fromCharCode(0),
colDelim = '","',
headDelim = '","',
rowDelim = '"\r\n"',
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
$heads = $row.find('th');
var c = $heads.map(function (k, head) {
var $head = $(head),
text = $head.text();
return text.replace(/"/g, '""');
}).get().join(tmpHeadDelim);
var d = $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""');
}).get().join(tmpColDelim);
return (c+d);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpHeadDelim).join(headDelim)
.split(tmpColDelim).join(colDelim) + '"';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
// if Internet Explorer (10+)
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});
window.navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
var blob = new Blob([csv],{type:'text/csv;charset=utf8'});
var url = URL.createObjectURL(blob);
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
}
}
$("#fnExcelReport").on('click', function (event) {
var args = [$('#tableContent'), 'Report.csv'];
exportTableToCSV.apply(this, args);
});
});
CodePen