This is a package for Meteor
json2csv allows you to generate a csv file from an array or a Meteor collection. This is useful for quick-and-dirty import/export or for spreading data in excel.
json2csv takes three arguments: json2csv(array, headings, quotes)
This could be any array, or a function that returns an array, such as Meteor's collection.find()fetch() function
// a simple array
[
{firstname: "Alex", lastname: "Webster"},
{firstname: "Jeff", lastname: "Wode"}
]
// a Meteor collection
Names.find().fetch()
// part of a Meteor collection
Names.find({firstname: "Alex"}, {sort: {lastname: -1}}).fetch()
Whether or not to include a header line of field names in the csv
Whether or not to wrap csv values in double quotation marks ""
See http://docs.meteor.com/#find and http://docs.meteor.com/#fetch for details on Meteor's collection.find().fetch() functions
// simply covert an array
var array = [
{firstname: "Alex", lastname: "Webster"}
{firstname: "Jeff", lastname: "Wode"}
]
var csv = json2csv(array, true, false)
// or return an entire Meteor collection
var csv = json2csv(Names.find().fetch(), true, true)
// or return part of a Meteor collection
var csv = json2csv(Names.find({firstname: "Alex"}, {sort: {lastname: -1}}).fetch(), true, true)
You could use this to add a 'download' button to a template as follows
<a href="#" class="btn btn-default" role="button" id="download">Download</a>
Template.orders.events({
'click #download': function (e) {
csv = json2csv(Orders.find().fetch(), true, true)
e.target.href = "data:text/csv;charset=utf-8," + escape(csv)
e.target.download = "orders.csv";
}
});
This is only intended for 'flat' files so you should filter collections accordingly.
json2csv is based substantially on Joseph Sturtevant's fiddle, which was in turn based on Zachary's stackoverflow answer
With Meteorite installed:
$ mrt add json2csv