Introduction
Voici comment importer un fichier CSV dans une application, puis le parser( décomposer) en un tableau javascript.
J’utilise pour ceci 2 librairies JQuery/Javascript :
1. http://hayageek.com/docs/jquery-upload-file.php
et
2. http://papaparse.com/
Tester en ligne :
http://nicolash.org/exercice15/
Le Code :
index.html
<meta http-equiv="content-type" content="text/html;charset=utf8" /> <!-- DEBUT DU CHARGEMENT DES LIBRAIRIES --> <!-- APPEL LIB JQUERY --> <script type="text/javascript" src="librairies/jquery.js"></script> <!-- APPEL LIB JQUERY UI ( look sympa du programme) --> <!-- <link href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> --> <script type="text/javascript" src="librairies/jquery-ui.js"></script> <link href="librairies/jquery-ui.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="librairies/jquery.dialogextend.js"></script> <!-- CHARGEMENT LIB UPLOADFILE --> <link rel="stylesheet" href="librairies/jquery-upload-file-master/css/uploadfile.min.css" type="text/css"/> <script src="librairies/jquery-upload-file-master/js/jquery.uploadfile.min.js" type="text/javascript" charset="utf-8"></script> <!-- FONCTIONS AJAX DU PROGRAMME --> <script type="text/javascript" src="fonctionsMachine.js"></script> <!-- CSS DU PROGRAMME --> <link rel="stylesheet" type="text/css" href="style.css" /> <!-- PAPAPARSE CSV TO JSON --> <script src="librairies/papaparse.js" type="text/javascript" ></script> <!-- FIN DU CHARGEMENT DES LIBRAIRIES --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Exercice 15</title> <body BGCOLOR=white> <img src="COMMANDIS.jpg" height=30px width=150px /> <!-- PAGE PRINCIPALE --> <div id="page" > <div id="info" >Les données vont apparaitre ici</div> <!-- ICONES --> <h3 id="clickMe2" id="draggable" class="icone" style="width:130px; background:tan; border:4px outset black;border-radius:5px;left: 400px; top:200px "> <img src="photoscommandis/exercice.jpg" height=100px width=100px />Parser un fichier CSV</h3> <!-- FENETRES --> <div id="dialog2" title="Lancer 1 lecture jquery ajax"> <div id="fileuploader">Télécharger votre fichier Csv</div> <div id="eventsmessage">debug</div> <!--zone du petit gif animé AJAX--> <img id="charge" src="chargeur.gif" width=50px /> <BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR> <!-- <button class="submit" type="submit" id="tbutton" >Requête Jquery Ajax</button> --> </div> <!-- FIN DE PAGE --> </body> </html>
fonctionMachines.js
// JavaScript Document // --------------------------------------------------- RECEPTION DES REQUETES AJAX ------------------------------------------------------ /* Requete En lecture Ajax JQUERY*/ $(function() { $("#tbutton").click(function(){ //gestion du bouton et du gif animé chargeur Ajax document.getElementById("tbutton").disabled= true; document.getElementById("charge").style.visibility="visible"; $.ajax({ url: 'afficher.php', type: "GET", data: "", success: function(data) { /* //code to execute */ document.getElementById("info").innerHTML=data; //affiche la zone info document.getElementById("info").style.visibility="visible"; alert('Requete ajax Jquery ok'); /* Fait disparaitre l'image du chargeur Ajax et réactive le button ! */ document.getElementById("tbutton").disabled= false; document.getElementById("charge").style.visibility="hidden"; } }); }); }); /* -----------------------------------------------RECEPTION DE FICHIER ET PARSING---------------------- */ /*Téléchargement du Fichier CSV */ /* http://hayageek.com/docs/jquery-upload-file.php */ $(document).ready(function() { $("#fileuploader").uploadFile({ url:"upload.php", fileName:"myfile", allowedTypes:"csv", /* Traduction */ dragDropStr: "<span><b>Faites glisser et deposez les fichiers</b></span>", abortStr:"abandonner", cancelStr:"resilier", doneStr:"fait", multiDragErrorStr: "Plusieurs Drag & Drop de fichiers ne sont pas autorises.", extErrorStr:"n'est pas autorisé. Extensions autorisees:", sizeErrorStr:"n'est pas autorisé. Admis taille max:", uploadErrorStr:"Upload n'est pas autorise", extErrorStr:"n'est pas autorise. Extensions autorisees:", onSubmit:function(files) { $("#eventsmessage").html($("#eventsmessage").html()+"<br/>Soumission:"+JSON.stringify(files)); }, onSuccess:function(files,data,xhr) { $("#eventsmessage").html($("#eventsmessage").html()+"<br/>Succes pour : "+JSON.stringify(data)); var nomFichier= JSON.stringify(files); /* PARSING CSV->JSON AVEC PAPAPARSE */ var nomFichier= nomFichier.replace('"',''); var nomFichier= nomFichier.replace('"',''); var nomFichier= nomFichier.replace('[',''); var nomFichier= nomFichier.replace(']',''); var nomFichier= "/exercice15/uploads/"+nomFichier; alert(nomFichier); Papa.parse(nomFichier, { download: true, complete: function(results) { console.log("Le fichier CSV a ete parse en un tableau javascript JSON", results); var tableau = results.data; /* document.write(results.data); */ $("#eventsmessage").html($("#eventsmessage").html()+"<br/>Voici les donnees parsees: "+results.data); } }); }, afterUploadAll:function(files) { $("#eventsmessage").html($("#eventsmessage").html()+"<br/>Tous les fichiers sont uploades"); }, onError: function(files,status,errMsg) { $("#eventsmessage").html($("#eventsmessage").html()+"<br/>Erreur pour: "+JSON.stringify(files)); } }); }); /* ----------------------------------------GENERATION DE TABLES ------------------------------------------------------------ */ /* ---------------------------------PLUGS IN DE FORMULAIRES --------------------------------------------------------------- */ /* --------------------------------------FENETRAGE et ICONES----------------------------------------------------------------------------- */ // Ouvre les fenetres sur clic d'icone $(function() { $('#clickMe2').click(function(event) { /* var mytext = $('#myText').val(); */ /* ligne dorigine tres inteeressante qui affiche une var supplemenaire dans la page (mytext) $('<div id="dialog2">'+mytext+'</div>').appendTo('body'); */ $('<div id="dialog2"></div>').appendTo('body'); event.preventDefault(); var dialog2Opts = {width:600, height:600, maxWidth: 800, maxHeight: 800, minWidth: 300, minHeight: 200,left: 100, top:10 ,autoOpen: true}; $( "#dialog2" ).dialog(dialog2Opts).dialogExtend({ "closable" : true, "maximizable" : true, "minimizable" : true, "collapsable" : true, "dblclick" : "collapse", "minimizeLocation" : "right", }); }); //close click }); $(function() { var dialogOpts = {width:400, height:400, maxWidth: 800, maxHeight: 800, minWidth: 300, minHeight: 200,left: 100, top:10 , autoOpen: false} ; $( "#dialog2" ).dialog(dialogOpts).dialogExtend({ "closable" : true, "maximizable" : true, "minimizable" : true, "collapsable" : true, "dblclick" : "collapse", "minimizeLocation" : "right", }); }); // Rends draggable les icones avec JQUERY $(function() { $( "#clickMe2" ).draggable(); });
essai.csv
paul;12345
pierre;45121
jacques ;467874
upload.php
<?php $output_dir = "uploads/"; if(isset($_FILES["myfile"])) { $ret = array(); // This is for custom errors; /* $custom_error= array(); $custom_error['jquery-upload-file-error']="File already exists"; echo json_encode($custom_error); die(); */ $error =$_FILES["myfile"]["error"]; //You need to handle both cases //If Any browser does not support serializing of multiple files using FormData() if(!is_array($_FILES["myfile"]["name"])) //single file { $fileName = $_FILES["myfile"]["name"]; move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName); $ret[]= $fileName; } else //Multiple files, file[] { $fileCount = count($_FILES["myfile"]["name"]); for($i=0; $i < $fileCount; $i++) { $fileName = $_FILES["myfile"]["name"][$i]; move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName); $ret[]= $fileName; } } echo json_encode($ret); } ?>
Publicités