Generate Csv For Excel Via Javascript With Unicode Characters
Solution 1:
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();
Solution 2:
The suggested solution didn't work with all browsers, but I found a way to get it working in all browsers (Chrome, Firefox, IE11 and even Edge, ... don't know about IE9-10 since I don't have access to them anymore).
I have to use an external library to encode encoding.js and it works amazingly well with unicode (I can see my unicorn emoji in my CSV export in Excel).
So here's the code
data = newTextEncoder('utf-16be').encode(csvContent);
// create a Blob object for the downloadconst blob = newBlob(['\uFEFF', data], {
type: 'text/csv;charset=utf-8';
});
// when using IE/Edge, then use different download callif (typeof navigator.msSaveOrOpenBlob === 'function') {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
// this trick will generate a temp <a /> tag that you can trigger a hidden click for it to start downloadingconst link = document.createElement('a');
const csvUrl = URL.createObjectURL(blob);
link.textContent = 'download';
link.href = csvUrl;
link.setAttribute('download', filename);
// set the visibility hidden so there is no effect on your web-layout
link.style.visibility = 'hidden';
// this part will append the anchor tag and remove it after automatic clickdocument.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
and that's it, it works in IE / Edge / Chrome / Firefox
Solution 3:
On a Node/Express server, I tried Shay's answer but I was getting an error for invalid characters in my header. Instead, I added the \uFEFF
to the beginning of the reply body and it worked.
app.get('/', function (req, res) {
var csv = Papa.unparse(...);
res.set({
'Content-Type': 'text/csv; charset=UTF-8',
'Content-Disposition': 'attachment; filename="file.csv"',
});
res.send('\uFEFF' + csv)
})
Post a Comment for "Generate Csv For Excel Via Javascript With Unicode Characters"