Part 1: Sencha Touch store to csv string

Freitag, 31. Januar 2014
I put a lot of research in this topic. The idea was to send a Sencha Touch store as csv by email to someone.

In this post I would like to show you the first step: generate CSV data from a store. There will be further post to this topic:

Part 2: Save csv string as csv file on the device
Part 3: Send csv file from device as email to recepients

If you have comments, questions or improvements please post them in the comment area!



The parameters are easy to understand:
// store: a reference to the store, which you want to send
// inFilter(optional): pass a filter function and the store will be filtered before taking data from it
// callback(optional): pass a callback function to use the csv data somewhere else

STORE2CSV: function (store, inFilter, callback) {
    var dataArray = new Array();

    if (inFilter === undefined || inFilter === null) {

        doBuild();

    } else {

        store.clearFilter();
        store.filter(inFilter);
        doBuild();

    }

    function doBuild() {

        store.load({
            callback: function (r, options, success) {
                if (success === true) {
                    store.each(function (item) {
                        dataArray.push(item.getData());
                    });
                    var csv = createCSV(dataArray);

                    if (callback !== undefined) {

                        callback(csv);

                    }
                }
            }
        });
    }

    function createCSV(objArray) {

        var array = typeof objArray != 'object' ? Ext.util.JSON.encode(objArray) : objArray,

            str = '',
            line = '',
            value = '',

            head = array[0]; // HEAD LINE

        for (var index in array[0]) {
            value = tryHeaderTranslate(index) + "";

            line += '"' + value.replace(/"/g, '""') + '",';
        }

        line = line.slice(0, -1);
        str += line + '\r\n';

        for (var i = 0; i < array.length; i++) {
            line = '';

            for (var index in array[i]) {
                value = array[i][index] + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }

            line = line.slice(0, -1);
            str += line + '\r\n';
        }
        return str;

    }

    // Try to translate the header
    function tryHeaderTranslate(header) {

        // you could translate or change the headers here if want to...
        return header;

    }
}