I need to export javascript array to CSV file and download it. I did it but 'ı,ü,ö,ğ,ş' this characters looks like 'ı ü ö ÄŸ ÅŸ' in the CSV file. I have tried many solutions recommended on this site but didn't work for me.
I added my code snippet, Can anyone solve this problem?
var csvString = 'ı,ü,ö,ğ,ş';
var a = window.document.createElement('a');
a.setAttribute('href', 'data:text/csv; charset=utf-8,' + encodeURIComponent(csvString));
a.setAttribute('download', 'example.csv');
a.click();
This depends on what program is opening the
example.csv
file. Using a text editor, the encoding will beUTF-8
and the characters will not be malformed. But usingExcel
the default encoding forCSV
isANSI
and notUTF-8
. So without forcingExcel
using notANSI
butUTF-8
as the encoding, the characters will be malformed.Excel
can be forced usingUTF-8
forCSV
with putting aBOM
(Byte Order Mark) as first characters in the file. The defaultBOM
forUTF-8
is the byte sequence0xEF,0xBB,0xBF
. So one could think simply putting"\xEF\xBB\xBF"
as first bytes to the string will be the solution. But surely that would be too simple, wouldn't it? ;-) The problem with this is how to force JavaScript to not taking those bytes as characters. The "solution" is using a "universal BOM""\uFEFF"
as mentioned in Special Characters (JavaScript).Example:
See also Adding UTF-8 BOM to string/Blob.
Using this, the encoding will be correct. But nevertheless, this only works properly if comma is the default list separator in your
Windows
locale settings. If not, if for example semicolon is the default list separator in yourWindows
locale settings, then all content will be in first column without splitting it by comma. Then you have to use semicolon as delimiter in theCSV
also. But this is another problem and leads to the conclusion not usingCSV
at all but using libraries which can directly creatingExcel
files (*.xls
or*.xlsx
).