Reputation: 1194
I read data from mysql database and then save it to csv file. I checked on the server side, the file is correctly saved with utf8 format. Then the user is prompted to download the file. When I download the file on my computer (MacOSX), the file is correct with utf8. (with file command in Termninal)
When I open the csv file in Excel, accented characters are wrong. In Excel, I have AZERTY√©a instead of AZERTYéa if I open the file with a text editor.
Here is my piece of code:
// File creation
var reportFile = Date.now();
fs.closeSync(fs.openSync(__dirname + '/reports/' + reportFile + '.csv', 'w'));
var attributes = [];
var row = [];
fs.appendFileSync(__dirname + '/reports/' + reportFile + '.csv', "\ufeff");
for(var x = 0; x<fields.length; x++) attributes.push(fields[x].name);
fs.appendFile(__dirname + '/reports/' + reportFile + '.csv', attributes.join('|'), function (err) {
if(err) console.log('Error appending fields', err);
fs.appendFileSync(__dirname + '/reports/' + reportFile + '.csv', '\n');
for(var x = 0; x<results.length; x++) {
row = [];
for(var y = 0; y<attributes.length; y++){
row.push(results[x][attributes[y]]);
}
fs.appendFileSync(__dirname + '/reports/' + reportFile + '.csv', row.join('|'));
fs.appendFileSync(__dirname + '/reports/' + reportFile + '.csv', '\n');
}
// file download
req.reportFile = reportFile;
res.setHeader('Content-disposition', 'attachment; filename='+__dirname + '/reports/' + reportFile + '.csv');
res.set('Content-Type', 'text/csv; charset=utf-8');
fs.readFile(__dirname + '/reports/' + reportFile + '.csv', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
res.header("Access-Control-Allow-Origin", "*");
res.status(200).send(data);
});
});
Upvotes: 1
Views: 344
Reputation: 1194
I finnaly found the solution. It was a BOM problem when sending the file. I tought that it was already set because I set it when writing the file....
I changed this line
res.status(200).send(data);
to
res.status(200).send('\ufeff'+data);
Upvotes: 2