我正在使用sas js http://sailsjs.org/#!documentation并且我想响应一个csv文件作为数据库查询的结果,如下所示:
module.exports = {
csv: function (req, res) {
Model.query("select * from somewhere ", function(err, list){
if (err) console.log(err);
// Send a CSV response
return res.csv(list);
});
},
_config: {}
};
这是可能的吗?
我已经尝试过:
csv: function (req, res) {
Model.query("select * from somewhere ", function(err, list){
if (err) console.log(err);
var objArray = list;
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
var head = array[0];
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
line = line.slice(0, -1);
str += line + '\r\n';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
line = line.slice(0, -1);
str += line + '\r\n';
}
res.setHeader('Content-disposition', 'attachment; filename=testing.csv');
res.writeHead(200, { 'Content-Type': 'text/csv' });
res.write(str);
return res;
});
}
但包括“parse”,“_ typeCast”
答案 0 :(得分:7)
var json2csv = require('json2csv');
var moment = require('moment');
module.exports = {
csv: function (req, res) {
MyModel.query("select id, name, email from MyModel", function(err, list){
if (err) console.log(err);
// Send a CSV response
var config = {
fields : ['id','name', 'email'],
data: list
};
json2csv(config, function(err, csv) {
if (err) console.log(err);
var filename = "report-" + moment().format("YYYY-MM-DD") + ".csv";
res.attachment(filename);
res.end(csv, 'UTF-8');
});
});
},
_config: {}
}
答案 1 :(得分:0)
这是我目前的解决方案,因为我无法删除我忽略的函数“_typeCast”和“parse”
csv:function(req,res){
Model.query("select * from somewhere ", function(err, list){ if (err) console.log(err); // Send a CSV response var array = list; var str = ''; var line = ''; var separator = ','; var head = array[0]; for (var index in array[0]) { if(index != "_typeCast" && index != "parse") line += escape(index) + separator; } line = line.slice(0, -1); str += line + '\r\n'; for (var i = 0; i < array.length; i++) { var line = ''; for (var index in array[i]) { if(index != "_typeCast" && index != "parse") line += escape(array[i][index]) + separator; } line = line.slice(0, -1); str += line + '\r\n'; } function escape( field ) { if (field == undefined) { return ''; } field = field + ""; return '"' + field.replace(/\"/g, '""') + '"'; } var filename = 'data.csv'; res.attachment(filename); res.end(str, 'UTF-8'); }); }
答案 2 :(得分:0)
如果使用Sails 1.0,则可以使用以下代码:
*