javascriptexcelcsvunicode

Generate CSV for Excel via JavaScript with Unicode Characters


I am trying to generate a CSV file on the client side using javascript. I've followed the answer on this stackoverflow question. I have unicode characters in the content (Hebrew characters in my case).

The file generation succeeds, however when I open the file in Excel - all the unicode characters are shown as funny characters. ASCII characters (English and numbers) are presented well.

The weird thing is that if I open the file in notepad, the unicode characters show well. So I guess this has something to do with Excel and the way I'm saving the file.

Any ideas?


Solution

  • Following Jack Cole's comment and this question, what fixed my problem was adding a BOM prefix (\uFEFF) to the beginning of the file.

    This is the working code:

    var csvContent = "...csv content...";
    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", "data:text/csv;charset=utf-8,\uFEFF" + encodedUri);
    link.setAttribute("download","report.csv");
    link.click();