6

I want to export my collection to a CSV or XLSX file by a button (no log-in system).

Is there a simple way to do that with Meteor/JavaScript?

4

3 回答 3

10

You could use something like https://github.com/eligrey/FileSaver.js to create a Blob on the browser side and then offer it as a download.

client side js

var yourCSVData = "Col1Row1,Col2Row1\nCol1Row2,Col2Row2";

var blob = new Blob([yourCSVData], 
                    {type: "text/csv;charset=utf-8"});
saveAs(blob, "yourfile.csv");

Build your CSV into yourCSVData then you should be able to have the file downloaded very easily.

To build your CSV you would have to use some custom javascript. The thing with mongodb is that each document can have a different structure, which is very bad for row/column type documents.

You could use something like the fiddle given by Yvegeniy (http://jsfiddle.net/sturtevant/vUnF9/) in the comments above & it might help

var data = MyCollection.find().fetch();
var yourCSVData = JSON2CSV(data);
于 2013-08-30T15:13:14.583 回答
1

Considering latest Meteor 1.5 and latest available Meteor packages as of today, below are the steps you need to follow in order to convert Mongo DB Collection to CSV (also readable by MS Office like a charm.)

  1. You need to have below packages installed prior to any steps below,

    pfafman:filesaver
    harrison:papa-parse
    
  2. Consider a simple Blaze Template (i.e. MyTemplate.html) with a download link below,

    <template name="MyTemplate">
      <body>
        <a href="#" role="button" class="download">Download</a>
      </body>
    </template>
    
  3. Similarly you can have events handler (i.e. in MyTemplate.js) to handle "Download" link click event,

    Template.MyTemplate.events({    
        'click .download': function (event, template) {
            var data = MyCollection.find({}).fetch();
            var csv = Papa.unparse(data);
            var blob = new Blob([csv],  {type: "text/csv;charset=utf-8"});
            saveAs(blob, "MyCollection.csv");
        }   
    }); 
    

NOTE- When you click the download link, you will not get any popup or dialog box for you to proceed downloading, rather it will automatically download it silently for you.

于 2017-06-30T10:02:39.443 回答
0

A template makes a perfectly good export system

    {{#each documents}}
    "{{field1}}","{{field2}}"<br/>
    {{/each}}

The xlsx format, while uglier, lends itself to the same treatment.

Rendering an HTML page is really the same thing. As is generating a pdf. Or generating SQL.

于 2013-08-30T18:49:19.180 回答