Separator in creating CSV from javascript is breaking special characters


Ask A Question





Login To post a question

I’m creating a CSV file with javascript. This is my code:

downloadCSV(data, filename) {
        var vm = this;
        var indexof;
        var array = typeof data != 'object' ? JSON.parse(data) : data;
        var str = '';

        //to generate the header
        var row = '';
        for (var i = 0; i < vm.exportColumnsArray.length; i++) {
            row += vm.exportColumnsLabelArray[i] + ';';
        }
        row = row.slice(0, -1);
        str += row + 'rn';

        // to generate the lines
        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var j = 0; j < vm.exportColumnsArray.length; j++) {
                if (line != '') {
                    line += ';';
                }
                if (array[i][vm.exportColumnsArray[j]]) {
                    if (typeof array[i][vm.exportColumnsArray[j]] !== 'object' &&
                        !(typeof array[i][vm.exportColumnsArray[j]] === 'string' &&
                            vm.exportColumnsArray[j].indexOf('@odata.context') != -1)) // the second validation is used to avoid adding information like '/odata/$metadata#LinkLists(4)/links'
                    {
                        line += """ + array[i][vm.exportColumnsArray[j]] + """;
                    }
                }
            }

            str += line + 'rn';
        }

        // Blob for IE.
        if (navigator.msSaveBlob) {
            navigator.msSaveBlob(
                new Blob([str], { type: 'text/csv;charset=utf-8;' }), filename
            );
            return;
        } else {
            var encoded = 'sep =;rn' + encodeURI(str);
            var element = document.createElement('a');
            element.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encoded);
            element.setAttribute('download', filename);
            element.style.display = 'none';
            document.body.appendChild(element);
            element.click();
            document.body.removeChild(element);
        }
    }

If I run this code and I have rare characters like japanese kanjis, they aren´t shown correctly. I have this character ‘醜’, which is URI encoded and it’s transformed in this: %E9%86%9C. But, when I open the CSV file with excel it shows ‘醜’. This is not very strange because %E9 = ‘é’, %86 = ‘†’ and %9C = ‘œ’. If I remove the separator…

'sep =;rn'

…the kanji is shown correctly. But I need the separator or the CSV won’t work in several regions.
Do you have any solution of this? Thanks.

For more info please click herehttps://stackoverflow.com/q/51259483



Have a question or need a custom quote?
info@smartinfocare.com