从Meteor导出数据到CSV的最简单方法是什么? 如何生成CSV?
添加Npm包:
$ meteor add meteorhacks:npm
添加Node.js CSV套件:
// packages.json
{
"csv": "0.4.0",
}
添加铁路由器包:
$ 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
答案 0 :(得分:2)
对于我的用例,所有数据都已发布到客户端。所以我决定使用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 = []
答案 1 :(得分:1)
使用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");
},