The below Code show how to download users data in CSV file. the issue is the output of the data inside the CSV is not organized.
app.js file
app.get('/export-csv',function(req,res){
db.query("SELECT * FROM users", function (err, users, fields) {
if (err) throw err;
console.log("users:");
const jsonUsers = JSON.parse(JSON.stringify(users));
//console.log(jsonUsers);
// -> Convert JSON to CSV data
const csvFields = ['id', 'name', 'shopCode','region'];
const json2csvParser = new Json2csvParser({ csvFields });
const csv = json2csvParser.parse(jsonUsers);
//console.log(users);
res.setHeader("Content-Type", "text/csv");
res.setHeader("Content-Disposition", "attachment; filename=users.csv");
res.status(200).end(csv);
});
});
what am I missing, how to make the data organized inside CSV ?
Try Instead of
const csvFields = ['id', 'name', 'shopCode','region'];
const json2csvParser = new Json2csvParser({ csvFields });
const csv = json2csvParser.parse(jsonUsers);
To
var fields = ['id', 'name', 'shopCode','region'];
var fieldNames = ['Id', 'Name', 'ShopCode','Region'];
var csv = json2csv({ data: docs, fields: fields, fieldNames: fieldNames });
and install json2csv npm. Hope it will work.