Ads

Thursday, May 17, 2012

Export CSV File in Titanium


One of my recent project I have exported tabular data into CSV file. In this post I will discuss about how to export CSV file in Appcelerator Titanium Application.

Here I have created a commonJS module for exporting tabular data into CSV file. The commonJs module function accept an argument and it export argument into CSV file.

The input argument(array) should be in following structure.
var input = [
    ["sample data 0", "sample data 1", "sample data 2"],
    ["sample data 0", "sample data 1", "sample data 2"],
    ["sample data 0", "sample data 1", "sample data 2"],
    ["sample data 0", "sample data 1", "sample data 2"]
];
In app.js add the below code
var csv = require('exportCsvData');

var win = Ti.UI.createWindow({
    backgroundColor:'#ccc',
    title:'CSV Import Module'
})

var createCsv = Titanium.UI.createButton({
    title:'Export CSV',
    top:'140',
    left:'110',
    height:'40',
    width:'115',
    color:'black'
});
win.add(createCsv);

win.open();

createCsv.addEventListener('click', function(e){
   var input = [
     ["sample data 0", "sample data 1", "sample data 2", "sample data 3"],
     ["sample data 0", "sample data 1", "sample data 2", "sample data 3"],
     ["sample data 0", "sample data 1", "sample data 2", "sample data 3"],
     ["sample data 0", "sample data 1", "sample data 2", "sample data 3"]
   ];
  
   var op = csv.exportCsvData(input);
   alert("Output file path = "+ op); 
});
Here is the code of exportCsvData.js which is a commonJS module
exports.exportCsvData = function(input)
{

    var rowTxt = "";
    for(var i=0;i < input.length; i++){ // row iteration
        for(var j = 0; j < input[i].length; j++){ // column iteration
            rowTxt += '"' + input[i][j] + '"';
 
            if(j < (input[i].length-1))
            {
                rowTxt += ',';
            }
        }
        rowTxt += '\n';// adding new line at end of row
    }

    // creating output file in application data directory
    var outputFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'output.csv');
    // writing data in output file 
        outputFile.write(rowTxt); 


    if(outputFile.exists){
        alert("CSV generated!!!");
    }
    
    // return output file path
    return outputFile.nativePath;    
}

this module will return the output CSV file path

1 comment: