Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to csv export encoding issue

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?

like image 319
Boltosaurus Avatar asked Oct 21 '13 11:10

Boltosaurus


People also ask

What is the best way to encode a CSV file in Excel?

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).

What is the default character encoding for a CSV file?

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.

Is it possible to use UTF-8 characters in a CSV file?

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.

Is it possible to Force Excel to use UTF-8 encoding?

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.


2 Answers

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

like image 157
Gergő Nagy Avatar answered Sep 20 '22 10:09

Gergő Nagy


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"

like image 34
Marcelo Lujan Avatar answered Sep 19 '22 10:09

Marcelo Lujan