如何导出csv nodejs
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18306013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to export csv nodejs
提问by Lion789
Hey I am trying to export a csv from node.js (pulling the data from mongodb). I already have the data being pulled and separated by commas and all, but now I am trying to figure out how to actually send it... I am sticking this code in my routes file. Any advice on how to take the array of data and send it to a user straight for download on request.
嘿,我正在尝试从 node.js 导出 csv(从 mongodb 中提取数据)。我已经将数据拉出并用逗号分隔,但现在我想弄清楚如何实际发送它......我将此代码粘贴在我的路由文件中。关于如何获取数据数组并将其直接发送给用户以根据请求下载的任何建议。
here is the code: (I attempted the the bottom part of the code the second function)
这是代码:(我尝试了代码的底部第二个功能)
exports.downloadContacts = function(req, res) {
async.waterfall([
function(callback) {
var source = [];
Friend.find({userId: req.signedCookies.userid}, function(err, friends) {
if(err) {console.log('err with friends for download');
} else {
var userMap = {};
var friendIds = friends.map(function (user) {
userMap[user.friend_id] = user;
return user.friend_id;
});
console.log(friends);
User.find({_id: {$in: friendIds}}, function(err, users) {
if(err) {console.log(err);
} else {
for(var i = 0; i < users.length; i++) {
console.log('users')
//console.log(users[i]);
source.push(users[i].firstNameTrue, users[i].lastNameTrue, users[i].emailTrue, users[i].phone, users[i].emailList, users[i].phoneList)
}
console.log(source);
callback(null, source);
}
});
}
});
}
],
function(err, source) {
var result = [];
res.contentType('csv');
csv()
.from(source)
.on('data', function(data){
result.push(data.join());
})
.on('end', function(){
res.send(result.join('\n'));
});
});
};
采纳答案by Jonathan P. Diaz
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>));
回答by Viet Tran
Here is what I did:
这是我所做的:
- Use json2csvto build csv data from mongodb data
- 使用json2csv从 mongodb 数据构建 csv 数据
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
- 向客户端发送csv数据
res.attachment('filename.csv');
res.status(200).send(data);
回答by d1jhoni1b
Hi guys based on @VierTD answer you have to use json2csv to build csv data from mongodb data
嗨,基于@VierTD 的回答,您必须使用 json2csv 从 mongodb 数据构建 csv 数据
Update Package.json with dependecies
使用依赖项更新 Package.json
"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
创建 json2CSV 对象,记住这是映射您的文档(db 表),因此“字段”上的名称必须与 db 表匹配,fieldNames 由您决定但也很重要,因为这些是 CSV 文件列名称
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
向客户端发送csv数据
res.attachment('filename.csv');
res.status(200).send(data);
This codeshows how to export csv file based on mongo db document (database table)
此代码显示了如何基于 mongo db 文档(数据库表)导出 csv 文件
I have created a github reporeally brief sampling the idea, also created a database with dummy data at Mongo Lab Websiteso this code will run inmediately in your computer.Based on @VietTD answer!
我已经创建了一个github repo对这个想法进行了非常简短的采样,还在Mongo Lab 网站上创建了一个带有虚拟数据的数据库,因此此代码将立即在您的计算机中运行。基于 @VietTD 答案!
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 ;D)
更改 db url(使用您自己的 db 这有效,但仅用于显示目的;D)
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
最后为您设置 CSV 标题列名称以及您的 CSV 文件名
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 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';
Thanks!
谢谢!
回答by ncthom91
I'm not totally sure what you're question is, but I think what you're looking for can be solved by setting the Content Disposition header. Take a look at this response on another another SO question: https://stackoverflow.com/a/7288883/2320243.
我不完全确定您的问题是什么,但我认为可以通过设置 Content Disposition 标头来解决您正在寻找的问题。在另一个 SO 问题上查看此回复:https: //stackoverflow.com/a/7288883/2320243。
回答by Federico
Express-csv is a great module for writing csv contents to stream from a node.js server, which will be sent as a response to the client (and downloaded as a file). Very easy to use.
Express-csv 是一个很棒的模块,用于将 csv 内容从 node.js 服务器写入流,它将作为响应发送到客户端(并作为文件下载)。非常容易使用。
app.get('/', function(req, res) {
res.csv([
["a", "b", "c"]
, ["d", "e", "f"]
]);
});
The docs: https://www.npmjs.com/package/express-csv
文档:https: //www.npmjs.com/package/express-csv
When you pass an object, you need to prepend the headers explicitly (if you want them). Here's my my example using npm mysql
当您传递一个对象时,您需要显式地预先添加标头(如果需要的话)。这是我使用npm mysql 的示例
router.route('/api/report')
.get(function(req, res) {
query = connection.query('select * from table where table_id=1;', function(err, rows, fields) {
if (err) {
res.send(err);
}
var headers = {};
for (key in rows[0]) {
headers[key] = key;
}
rows.unshift(headers);
res.csv(rows);
});
});
回答by svarrall
The json2csvpackage has been updated since the highest voted answer was written, the newer version has slightly different syntax:
该json2csv软件包已被更新以来的最高投票的答案是书面的,较新的版本稍有不同的语法:
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.
res.attachment 是一个函数而不是一个属性。需要删除等号才能工作。
回答by Chuong Tran
I found a solution at this http://nikgrozev.com/2017/05/10/mongo-query-to-CSV-download-expressjs/
我在这个http://nikgrozev.com/2017/05/10/mongo-query-to-CSV-download-expressjs/找到了一个解决方案
Keyword
关键词
stream the output to the HTTP response
将输出流式传输到 HTTP 响应
回答by aabiskar
Using json2csv library you can export csv from mongodb data.
使用 json2csv 库,您可以从 mongodb 数据导出 csv。
const json2csv = require('json2csv').parse;
//For unique file name
const dateTime = new Date().toISOString().slice(-24).replace(/\D/g,
'').slice(0, 14);
const filePath = path.join(__dirname, "../../../", "public", "exports", "csv-"
+ dateTime + ".csv");
let csv;
const student = await req.db.collection('Student').find({}).toArray();
// Logging student
// [{id:1,name:"John",country:"USA"},{id:1,name:"Ronny",country:"Germany"}]
const fields = ['id','name','country'];
try {
csv = json2csv(booking_info, {fields});
} catch (err) {
return res.status(500).json({err});
}
fs.writeFile(filePath, csv, function (err) {
if (err) {
return res.json(err).status(500);
}
else {
setTimeout(function () {
fs.unlink(filePath, function (err) { // delete file after 30 sec
if (err) {
console.error(err);
}
console.log('File has been Deleted');
});
}, 30000);
res.download(filePath);
}
})

