我想下载从具有以下条目的数据库 (nodeDB) 生成的 CSV 文件。
这些条目应仅作为标题。
{
"META": {
"TEMPLATE_NAME": "B",
"TEMPLATE_GROUP": "Product",
"KEYWORDS": [
"cc"
],
"TEMPLATE_SUBGROUP": ""
},
"VARIENTS": [
{
"NAME": "Brand",
"DATATYPE": "Text",
}
]
}
我编写了以下代码:
HTML:
<template name="templateForCSV">
<a href="{{pathFor 'csv'}}" target="_blank">Download the CSV</a>
</template>
JS:
if (Meteor.isServer) {
Meteor.startup(function () {
//CSV Download
var DataCursor=nodeDB.find({});
if (DataCursor.count() === 0) {
for(var i=1; i<=DataCursor.length; i++) {
//Example for Now, has to be changed
nodeDB.insert({Brand: "Brand" + i,Price: "Price" + i, Description:"Description" + i});
}
}
});
}
Router.route('/csv', {
where: 'server',
action: function () {
var filename = 'data.csv';
var fileData = "";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
var records = nodeDB.find();
// This is the main problem. build a CSV string. Oversimplified. You'd have to escape quotes and commas.
records.forEach(function(rec) {
fileData += rec.META + "," + rec.VARIENTS + "," + "\r\n";
});
this.response.writeHead(200, headers);
return this.response.end(fileData);
}
});
CSV 文件已下载,但为空白。发生了什么?
最佳答案
首先,假设您的 nodeDB
工作正常。您的问题可能是没有为 /csv
定义路由,所以只需尝试下面的测试。
<template name="templateForCSV">
<a href="/csv" target="_blank">Download the CSV</a>
</template>
如果仍然是空白,我猜你的
nodeDB
是空白的,所以尝试下面的测试。Router.route('/csv', function () {
var filename = 'data.csv';
var fileData = "hello, world";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
this.response.writeHead(200, headers);
this.response.end(fileData);
}, {where: "server"});
应下载带有“hello, world”的 CSV 文件。请注意,我将上面的语法稍微更改为我使用的语法。
试试这个,让我们知道它是否有效。
关于csv - 如何使用meteor将存储在DB中的json转换为csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30613182/