I need to export javascript array to excel file and download it I'm doing it in this code. data is a javascript object array.
var csvContent = "data:text/csv;charset=utf-8,"; data.forEach(function(dataMember, index) { dataString = dataMember.join(","); csvContent += index < data.length ? dataString+ "\n" : dataString; }); var encodedUri = encodeURI(csvContent); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "upload_data" + (new Date()).getTime() + ".csv"); link.click();
All this stuff works fine till I have string properties that have non-english characters, like spanish, arabic or hebrew. How can I make an export with all this non-ASCII values?
Excel is really bad at detecting encoding, especially Excel on OSX. The best solution would be to encode your CSV in the default Excel encoding: windows-1252 (also called ANSI, which is basically a subset of ISO-8859-1).
But using Excel the default encoding for CSV is ANSI and not UTF-8. So without forcing Excel using not ANSI but UTF-8 as the encoding, the characters will be malformed.
But using Excel the default encoding for CSV is ANSI and not UTF-8. So without forcing Excel using not ANSI but UTF-8 as the encoding, the characters will be malformed. Excel can be forced using UTF-8 for CSV with putting a BOM ( Byte Order Mark) as first characters in the file. The default BOM for UTF-8 is the byte sequence 0xEF,0xBB,0xBF.
So without forcing Excel using not ANSI but UTF-8 as the encoding, the characters will be malformed. Excel can be forced using UTF-8 for CSV with putting a BOM ( Byte Order Mark) as first characters in the file.
You should add the UTF-8 BOM at the start of the text, like:
var csvContent = "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent);
It worked for me with Excel 2013.
Demo Fiddle
You can add the BOM at first, use this code and try
var BOM = "\uFEFF"; var csvContent = BOM + csvContent;
and then crate the file headers with the data: "text/csv;charset=utf-8"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With