Export CSV data with # character in JavaScript does not work
Asked Answered
N

1

7

I export JSON data to CSV format and download it with JavaScript. Everything works fine except if the data has the hash sign #. The function does not export all data, for example:

this is my first C# lesson in the academy, it exports only this is my first C and ignore the rest of it.

This is my code

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);
        }
    }
};
Neoimpressionism answered 23/3, 2021 at 16:28 Comment(1)
Note that # is not "the sharp character". The actual sharp character is ♯. The # character (notice the subtle difference) is called the number sign, hash, or pound sign. The # is commonly used with the C♯ programming language, because there's not a simple way to type the ♯ character.Compotation
S
9

encodeURI encodes characters which are forbidden in a URI, not ones which have special meaning.

The # won't be encoded but it starts the fragment identifier portion of the URI.

Use encodeURIComponent instead.

Stonewort answered 23/3, 2021 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.