gpt4 book ai didi

javascript - 从 Meteor.js 集合创建 CSV 文件

转载 作者:IT老高 更新时间:2023-10-28 13:35:26 25 4
gpt4 key购买 nike

到目前为止,我已经编写了我的代码,并且可以获得要显示在网页上的所有记录的列表,但是我需要能够将其作为 CSV(逗号分隔值)文件来获取。

现在页面显示如下列表:

Name      Address      Description
Bob 1 street Journalist
Bill 2 street Fireman
etc...

无论如何,我可以让 meteor 创建一个 CSV 文件以供下载,而不是显示为带有所有 HTML 标记的网页?

最佳答案

基于 How to serve a file using iron router or meteor itself?

HTML:

<template name="blah">
<a href="{{pathFor 'csv'}}">Download the CSV</a>
</template>

JS:

// An example collection
var DummyData = new Mongo.Collection("dummyData");

// create some sample data
if (Meteor.isServer) {
Meteor.startup(function() {
var dummyDataCursor = DummyData.find();
if (dummyDataCursor.count() === 0) {
for(var i=1; i<=100; i++) {
DummyData.insert({Name: "Name" + i,Address: "Address" + i, Description:"Description" + i});
}
}
});
}

Router.route('/csv', {
where: 'server',
action: function () {
var filename = 'meteor_dummydata.csv';
var fileData = "";

var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
var records = DummyData.find();
// build a CSV string. Oversimplified. You'd have to escape quotes and commas.
records.forEach(function(rec) {
fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n";
});
this.response.writeHead(200, headers);
return this.response.end(fileData);
}
});

关于javascript - 从 Meteor.js 集合创建 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27238457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com