How to export csv nodejs
Here is what I did:
- Use json2csv to build csv data from mongodb data
var json2csv = require('json2csv');
var fields = ['name', 'phone', 'mobile', 'email', 'address', 'notes'];
var fieldNames = ['Name', 'Phone', 'Mobile', 'Email', 'Address', 'Notes'];
var data = json2csv({ data: docs, fields: fields, fieldNames: fieldNames });
- Send csv data to client
res.attachment('filename.csv');
res.status(200).send(data);
Based on @VierTD answer, you have to use json2csv to build csv data from mongodb data.
Update Package.json with dependecies:
"dependencies": {
"mongodb": "^2.2.10",
"json2csv": "*",
"express": "*"
}
Create the json2CSV object, remember this is mapping your document (db table) so names on "fields" must match db table, fieldNames are up to you but are also important since these are the CSV file column names:
var json2csv = require('json2csv');
var fields = ['name', 'phone', 'mobile', 'email', 'address', 'notes'];
var fieldNames = ['Name', 'Phone', 'Mobile', 'Email', 'Address', 'Notes'];
var data = json2csv({ data: docs, fields: fields, fieldNames: fieldNames });
Send csv data to the client:
res.attachment('filename.csv');
res.status(200).send(data);
This code shows how to export csv file based on mongo db document (database table)
I have created a github repo really brief sampling the idea, also created a database with dummy data at Mongo Lab Website so this code will run inmediately in your computer.Based on @VietTD answer.
In case you are interested on testing this code just remember to change following lines.
Change db url (User your own db this works but it's only for showing purposes).
var url = 'mongodb://admin:[email protected]:63946/misale_dev';
Change target document (or db table).
var collection = db.collection('_dummy');
Change document columns (or db table's column fields):
var fields = ['_id', 'JobID', 'LastApplied'];
Finally set you CSV title column names as well as your CSV file name:
var fieldNames = ['ID_OR_PK', 'JOB_UNIQUE_ID_TITLE', 'APPLICATION_DATE'];
Last but not least:
res.attachment('yourfilenamehere.csv');
Please feel free to improve the sample code i'll appreciate that! or just download it and take a look at the code. It already comes with a database, so it will be easy to understand and run, in such a case you dont care here is the whole code maybe you see something interesting:
//
// EXPRESS JS SERVER INITI
//
var express = require('express')
var app = express()
//
// MONGO DB INIT
//
var MongoClient = require('mongodb').MongoClient, assert = require('assert');
app.get('/', function (req, res) {
var url = 'mongodb://admin:[email protected]:63946/misale_dev';
//
// This function should be used for migrating a db table to a TBD format
//
var migrateMongoDBTable = function(db, callback) {
// Get the documents collection
console.log("Reading database records");
// Get the documents collection
var collection = db.collection('_dummy');
// Find some documents
//collection.find({'a': 3}).toArray(function(err, docs) {
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
//console.log(docs);
//console.log('docs.length ---> ', docs.length);
console.log('Creating CSV...');
//console.log('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=');
var json2csv = require('json2csv');
var fields = ['_id', 'JobID', 'LastApplied'];
var fieldNames = ['ID_OR_PK', 'JOB_UNIQUE_ID_TITLE', 'APPLICATION_DATE'];
var data = json2csv({ data: docs, fields: fields, fieldNames: fieldNames });
//console.log('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=');
// EXPORT FILE
res.attachment('yourfilenamehere.csv');
res.status(200).send(data);
callback(docs);
});
};
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
//
// migrate db table to some format TBD
//
migrateMongoDBTable(db, function() {
db.close();
});
});
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
// Connection URL
//var url = 'mongodb://localhost:27017/myproject';
The json2csv package has been updated since the highest voted answer was written, the newer version has slightly different syntax:
var { Parser } = require('json2csv')
const fields = [{
label: 'header 1',
value: 'field1_name'
}, {
label: 'header 2',
value: 'field2_name'
}]
const json2csv = new Parser({ fields: fields })
try {
const csv = json2csv.parse(data)
res.attachment('data.csv')
res.status(200).send(csv)
} catch (error) {
console.log('error:', error.message)
res.status(500).send(error.message)
}
res.attachment is a function and not an attribute. Needed to remove the equal sign for this to work.
Have you tried something like this with a content type as "application/octet-stream"
res.set('Content-Type', 'application/octet-stream');
res.send(<your data>);
or simply
res.send(Buffer.from(<your data>));
Express send() docs.