最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating a CSV file from a Meteor.js Collection - Stack Overflow

programmeradmin5浏览0评论

I've written my code so far and can get a list of all the records to show up on a webpage, however I need to be able to get it as a CSV (ma separated values) file.

Right now the page shows a list like follows:

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

Anyway I can have meteor create a CSV file for download, instead of it showing up as a webpage with all the HTML markup?

I've written my code so far and can get a list of all the records to show up on a webpage, however I need to be able to get it as a CSV (ma separated values) file.

Right now the page shows a list like follows:

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

Anyway I can have meteor create a CSV file for download, instead of it showing up as a webpage with all the HTML markup?

Share Improve this question asked Dec 1, 2014 at 22:22 npderinpderi 792 silver badges6 bronze badges 1
  • possible duplicate of How to serve a file using iron router or meteor itself? – David Weldon Commented Dec 1, 2014 at 22:41
Add a ment  | 

1 Answer 1

Reset to default 8

Based on 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 mas.
    records.forEach(function(rec) {
      fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n";
    });
    this.response.writeHead(200, headers);
    return this.response.end(fileData);
  }
});
发布评论

评论列表(0)

  1. 暂无评论