clinical:csv
Utilities for importing and exporting comma separated value (CSV) files.
========================== ####Package Installation
meteor add clinical:csv
======================================
Simple Export (client)
1Template.fooPage.events({ 2 "click #downloadButton":function(){ 3 var csvContent = CSV.unparse(Posts.find().fetch()); 4 window.open('data:text/csv;charset=utf-8,' + escape(csvContent), '_self'); 5 } 6});
========================== ####Parsing/Unparsing CSV
See the PapaParse documentation: http://papaparse.com/
1// Parse CSV string 2var data = CSV.parse(csv); 3 4// Convert back to CSV 5var csv = CSV.unparse(data); 6 7// Parse local CSV file 8CSV.parse(file, { 9 complete: function(results) { 10 console.log("Finished:", results.data); 11 } 12}); 13 14// Stream big file in worker thread 15CSV.parse(bigFile, { 16 worker: true, 17 step: function(results) { 18 console.log("Row:", results.data); 19 } 20});
========================== ####Import CSV (Server)
Given a CSV file like the following (simple.csv)
1;01;ozan;OZAN;Ozan;O250;OSN;01190;284;01284;2;26;6;618;469;500;94;660;4.91667;46.3833;2866;51546;+45456;462330;170;205;14126;8823;26916 2;01;marboz;MARBOZ;Marboz;M612;MRBS;01851;232;01232;2;11;6;2182;2164;2200;54;4014;5.25;46.3333;3246;51492;+51530;462033;194;240;4580;14287;1768 3;01;foissiat;FOISSIAT;Foissiat;F230;FST;01340;163;01163;2;21;6;1912;1562;1900;47;4036;5.18333;46.3667;3153;51523;+51029;462213;186;228;5227;15952;1738
You can use server-side code synchronous to load the file line-by-line
1 CSV.readCsvFileLineByLine('simple.csv', function (line, index, rawParsedLine) { 2 lines.push(line); 3 }); 4 5 //lines[0][1] === "01";
If you want to insert in your collection, you need to wrap your insert, to make sure your code will be run synchronuously:
1 CSV.readCsvFileLineByLine('simple.csv', Meteor.bindEnvironment(function (line, index, rawParsedLine) { 2 Collection.insert({ 3 property: line.property 4 })); 5 });
If you have more complex CSV files, with headers and escaping chars:
"id":"firstName":"lastName" "1":"jimi":"hendrix" "2":"jim":"morrison"
You can simply add options to make it simple (refer to papa docs : http://papaparse.com/docs#config)
1 CSV.readCsvFileLineByLine(process.env.PWD + '/vicious.csv', { 2 headers: true, 3 delimiter: ":", 4 }, function (line) { 5 lines.push(line); 6 }); 7 8 //lines[0].firstName === "foo"; 9 //lines[1].firstName === "jim";
==========================
Fetch CSV From Server
Sometimes you'll want to fetch a CSV from a server-side collection. Be careful with this, as Mongo collection can be large!
Meteor Methods that Return CSV (server)
Meteor.methods({ download: function() { return CSV.unparse(CollectionToExtract.find().fetch()); }, customDownload: function(){ var collectionData = CollectionToExtract.find().fetch(); var heading = true; // Optional, defaults to true var delimiter = ";" // Optional, defaults to ","; return CSV.unparse(collectionData, heading, delimiter); } });
Fetch CSV From Server and then Download (client)
//events 'click #buttonDownload': function(event) { var nameFile = 'fileDownloaded.csv'; Meteor.call('download', function(err, fileContent) { if(fileContent){ var blob = new Blob([fileContent], {type: "text/plain;charset=utf-8"}); saveAs(blob, nameFile); } });
Known issues
- Documents need to have an identical length of elements.
- Objects are not displayed (export JSON instead).
====================================
Select File and Parse on Client
1<template name="example"> 2 <div id="example> 3 <button id="uploadCsv"></button> 4 <input id="hiddenUpload" class="btn hidden" type="file" value="Hidden Upload"> 5 </div> 6</template>
1Template.example.events({ 2 'click #uploadCsv': function(){ 3 $('#hiddenUpload').click(); 4 }, 5 'change #hiddenUpload': function(event, template){ 6 var filesList = event.currentTarget.files; 7 if (filesList.length) { 8 console.log('filesList', filesList); 9 10 var file = filesList[0]; 11 console.log('file', file); 12 13 if (file.type === 'text/csv') { 14 var fileReader = new FileReader(); 15 fileReader.onload = function (e) { 16 var jsonRepresentationOfCsv = CSV.parse(fileReader.result); 17 console.log('jsonRepresentationOfCsv', jsonRepresentationOfCsv); 18 Session.set('uploadedData', jsonRepresentationOfCsv); 19 }; 20 fileReader.onerror = function (e) { 21 throw 'Error reading CSV file'; 22 }; 23 24 fileReader.readAsText(file); 25 } 26 } 27 } 28})
========================== ####Acknowledgements
https://github.com/mholt/PapaParse
https://github.com/evaisse/meteor-csv
https://github.com/lfergon/meteor-export-csv
https://github.com/eligrey/FileSaver.js
========================== ####Licensing