【问题标题】:Export CSV/XLS from Meteor application从 Meteor 应用程序导出 CSV/XLS
【发布时间】:2014-11-09 05:28:18
【问题描述】:

从 Meteor 将数据导出到 CSV 的最简单方法是什么? 如何生成 CSV?

我尝试过的

添加 Npm 包:

$ meteor add meteorhacks:npm

添加 Node.js CSV 套件:

// packages.json

{
  "csv": "0.4.0",
}

添加 Iron Router 包:

$ meteor add iron:router

server上配置路由器:

// server/router.coffee

Router.map ->
  @route 'exportCSV',
    where: 'server'
    path: '/export-csv/:id'
    onAfterAction: ->
      data = ... // Generated CSV 
      filename = 'filename.csv'
      headers =
        'Content-type': 'text/csv'
        'Content-Disposition': 'attachment; filename=' + filename
      @response.writeHead 200, headers
      @response.end file

【问题讨论】:

    标签: csv meteor npm export-to-csv iron-router


    【解决方案1】:

    对于我的用例,所有数据都已发布给客户端。所以我决定在那里生成文件,使用FileSaver

    这是一个基本类,通过调用 addRow() 构建 csv,然后调用 download('xxx.csv') 让用户下载文件。

    class CsvBuilder
    
      constructor: ->
        @content = []
    
      line: ->
        row = [].slice.call(arguments)
        if row.length  == 0
          @addBlankRow()
        else
          @addRow(row)
        return
    
      addRow: (row)->
        @content.push(@row2Csv(row), "\n")
        return
    
      addBlankRow: ->
        @content.push("", "\n")
        return
    
      row2Csv: (row)->
        d = ''
        for cell in row
          d += '"' + (cell + "").replace(/"/g, '""') + '",'
        return d
    
      download: (filename)->
        try
          isFileSaverSupported = !!new FileSaver.Blob()
    
        unless isFileSaverSupported
          window.alert("Save as CSV not supported");
          return
    
        contentBlob = new FileSaver.Blob(@content, {type: "text/csv;charset=utf-8"})
        FileSaver.saveAs(contentBlob, filename)
        return
    
      destroy: ->
        @content = []
    

    【讨论】:

      【解决方案2】:

      使用来自 eligrey/Filesaver 的 FileSave.js 并保存在您客户端的 lib 文件夹中

      'click .btnRawCSV' : function() {
          var rawData = Gifts.find({
                                    receiptdate:{
                                               $gte: Session.get("giftsStartDate"),
                                               $lte: Session.get("giftsEndDate")
                                                }
                                      }).fetch();
          csv = json2csv( rawData, true, true );
          var blob = new Blob([csv], {type: "text/plain;charset=utf-8;",});
      
          saveAs(blob, "rawgifts.csv");    
      },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-03
        • 1970-01-01
        • 2012-12-19
        • 1970-01-01
        • 2018-06-05
        • 2017-06-23
        • 1970-01-01
        • 2017-12-01
        相关资源
        最近更新 更多