0

I've an array of data which is converted to a csv file using javascript.

Some data values have weird characters (f.e.: ù and õ). These characters are supported by UTF-8, which is the character set I use for my csv encoding. But still these weird letters are displayed wrong in my resulting csv file.

For example the variables Name ( à , ù, ë ) and Juònùõ become:

example wrong formatting

How can I fix this?

This is my code (based on question: How to export JavaScript array info to csv (on client side)?):

var data = [
    ["Name ( à , ù, ë )"],
    ["Juònùõ"]
]
var csvContent = '';
data.forEach(function(infoArray, index) {
    dataString = infoArray.join(';');
    csvContent += index < data.length ? dataString + '\n' : dataString;
});



var download = function(content, fileName, mimeType) {
    var a = document.createElement('a');
    mimeType = mimeType || 'application/octet-stream';

    if (navigator.msSaveBlob) { // IE10
        navigator.msSaveBlob(new Blob([content], {
            type: mimeType
        }), fileName);
    } else if (URL && 'download' in a) { //html5 A[download]
        a.href = URL.createObjectURL(new Blob([content], {
            type: mimeType
        }));
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    } else {
        location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
    }
}

download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8,{header:true}');
Daan Seuntjens
  • 880
  • 1
  • 18
  • 37
  • 1
    i think the problem is the program that you are using to view the cvs file. It shows the right characters for me. – Johnny Zabala Feb 08 '20 at 16:17
  • 1
    You can try inserting a byte order mark at the start of your CSV by intitializing csvContent like this: `var csvContent = '\uFEFF';`'. Some programs tend to recognize files as UTF-8 encoded more easily when they start with the BOM. On the other hand, the BOM tends to mess up headers when importing CSV files into some programs. – Petr Srníček Feb 08 '20 at 16:43
  • I was using excel to open the csv file. Using "csvContent = '\uFEFF';" it works! If @PetrSrníček posts this as an answer I will accept it :) – Daan Seuntjens Feb 08 '20 at 16:50

1 Answers1

2

You can try inserting a byte order mark at the start of your CSV by intitializing csvContent like this: var csvContent = '\uFEFF';. Some programs tend to recognize files as UTF-8 encoded more easily when they start with the BOM. On the other hand, the BOM tends to mess up headers when importing CSV files into some programs.

Petr Srníček
  • 2,296
  • 10
  • 22