When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example:
This is my first C# lesson in the academy, but it only exports "this is my first C" and ignores the rest of it.
Below is an example of the code being used:
this.handleRow = function (row) {
var finalVal = '';
for (var j = 0; j < row.length; j++) {
var innerValue = "";
if (row[j]) {
innerValue = row[j].toString();
}
if (row[j] instanceof Date) {
innerValue = row[j].toLocaleString();
}
var result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0) {
result = '"' + result + '"';
}
if (j > 0) finalVal += ',';
finalVal += result;
}
return finalVal + '\n';
};
this.jsonToCsv = function (filename, rows) {
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += this.handleRow(rows[i]);
}
var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;'});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = $window.document.createElement("a");
if (typeof link.download === "string") {
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvFile));
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
$window.document.body.appendChild(link);
link.click();
$window.document.body.removeChild(link);
}
}
};