Reputation:
What is the simplest way to export data to CSV from Meteor? How to generate CSV?
Add Npm package:
$ meteor add meteorhacks:npm
Add Node.js CSV suite:
// packages.json
{
"csv": "0.4.0",
}
Add Iron Router package:
$ meteor add iron:router
Configure router on 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
Upvotes: 0
Views: 2377
Reputation: 132
Using the FileSave.js from eligrey/Filesaver and save in lib
folder in you client
'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");
},
Upvotes: 1
Reputation: 8865
For my use-case, all of the data was already published to the client. So I decided to generate the file there, using FileSaver.
Here's a basic class to build a csv by calling addRow()
, then call download('xxx.csv')
to have the user download the file.
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 = []
Upvotes: 2