Accented letters not showing properly when exporting CSV using javascript

2.5k views Asked by At

I am doing an export to CSV functionality on my website. The data are in spanish so there will be alot of accented characters in there, and one example of this problem is the header "Año" (year) but on excel it shows as "Año".

Here is my export code using javascript:

HTML

<a href="#" class="btn" id="export-btn"> Export</a>
<a href="#" class="btn" id="download" style="display:none"> Download Now </a>

JS

$(document).on('click', '#export-btn', function(e) {

    var _this = $(this);
    _this.attr('disabled',true);

    var datenow = new Date();
        datenow = datenow.getTime();

    var exportdata = ConvertToCSV(exportdata);

    $('#download').attr("href", "data:text/csv;charset=utf8," + encodeURIComponent(exportdata) );
    $('#download').attr("download", "InTrack-Report-"+datenow+".csv");

    $('#download').show(); //show download button

    _this.attr('disabled',false);

});

here is the ConvertToCSV function, I added sep=; to make excel recognize the semicolon as delimiters.

function ConvertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = 'sep=;\r\n'; //tell excel that we used semicolon as separator

    //header
    var line = '';
    for (var i = 0; i < array.Fields.length; i++) {
        if (line != '') line += ';'
        line += array.Fields[i]['Title'];
    }
    str += line + '\r\n';

    //rows
    for (var i = 0; i < array.Rows.length; i++) {
        var line = '';
        for (var index in array.Rows[i]) {
            if (line != '') line += ';'

            line += array.Rows[i][index];
        }

        str += line + '\r\n';
    }

    return str;
}


UPDATE: I found a way to display the accented letters properly by following the solution here. But I had to remove the sep=; which is important as it separates my data by semicolon. Is there a way to add both the BOM and the sep=; at the top? If so, how? Because it seems like I can only use one.

So instead of str='sep=;\r\n' it is now str='\uFEFF sep=;\r\n'

2

There are 2 answers

0
L. GARG On

Use escape at place of encodeURI and add "sep=;\n" before string and allow it to escape as well

Sample code

var csvString =  "sep=;\n" + csvRows.join("\n");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv;charset=UTF-8,%EF%BB%BF' + escape(csvString);
0
Marcelo Lujan On

if you get an error with the ASCII in the creation of file.csv, try adding the BOM first.

var BOM = "\uFEFF"; 
return BOM + str;

and then crate the file headers with the data: "text/csv;charset=utf-8" instead of utf8 (without - )