Search code examples
phonegap-pluginsphonegap-buildcordova-pluginsexport-to-csvcordova-2.0.0

How to create csv or Excel file using javascript in Cordova android app


I am trying to create android app using phoneGap. I have written code for creating csv file in javascript ,which works fine on browser,but its not working in mobile app created using cordova.Everything other than file creation works fine in cordova app.Pl. guide

I have used following permissions in manifest,

Code for creating csv file:- var link = document.getElementById("dataLink");

        var csv = "";
            //we should have the same amount of name/cookie fields

                var name = "testdata1";
                var cookies = "testdata2",
                csv = csv + ""+ name + "," + cookies + "\n";    

                    console.log("csv-"+csv);

                    $("#dataLink").attr("href", 'data:Application/octet-stream,' + encodeURIComponent(csv))[0].click();


Solution

  • You will need to use the File Plugin of Crodova to write file to the file system as different Operating System have only certain directories accessible to the Application to read/write.

    The code to create the file object and writing will look something like this

    window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dir) {
       console.log("got main dir", dir);
       dir.getFile("myfile.csv", {
         create: true
       }, function(file) {
         console.log("got the file", file);
         logOb = file;
         var csv = "";
         //we should have the same amount of name/cookie fields
         var name = "testdata1";
         var cookies = "testdata2",
           csv = csv + "" + name + "," + cookies + "\n";
         console.log("csv-" + csv);
         writeLog(csv);
       });
     });
    
     function writeLog(str) {
       if (!logOb) return;
       logOb.createWriter(function(fileWriter) {
         fileWriter.seek(fileWriter.length);
    
         var blob = new Blob([str], {
           type: 'text/plain'
         });
         fileWriter.write(blob);
         console.log("ok, in theory i worked");
       }, fail);
     }
    

    You can refer to this tutorial to better understand the process of file writing.