Get Excel to open your CSV with utf-8 support
I am from Sweden so we have extra non-ascii friendly characters å, ä and ö in our alphabet. So does most of the european countries or they have something equivalent to that like æ, ç etc.
However when producting a CSV file recently that were going to be opened with Excel there quickly became appearant that Excel did not open the file in the UTF-8 format the file was saved in. However, I found a quick an easy way to make Excel default to opening the file in UTF-8.
By adding the UTF-8 BOM character (\uFEFF
) to the beginning of the file, Excel will automatically open the file as the UTF-8 file you stored it as.
Here is the code to generate the CSV file and download it automatically in the browser with javascript:
const csv = [
{
'Hello': 'world',
'Hej': 'världen'
},
{
'Bye': 'world',
'Hejdå': 'världen'
}
];
const columns = Object.keys(csv);
const rows = [
'\uFEFF', // The magic BOM character
[columns.join(';')],
...csv.map(r => {
return Object.values(r).join(';');
})
];
const file = new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(file);
link.href = url;
link.download = 'data.csv';
document.body.appendChild(link);
link.click();
setTimeout(function () {
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}, 0);
I hope my code solves your issues but please be aware that it's browser specific code to generate the CSV file and will not work in a node.js environment.