Project

Contents

Issue #00005120

Added AFW.Util.csvReader()
AFW
Feature/Improvement

We already have AFW.Util.csvWriter() to export data in csv format.

We now added a csv importer:

AFW.Util.csvReader(config).read(stream_or_file[, encoding])

Config options:

columns:                Array of column definitions. Required.
dateFormat:             Optional date format. If empty yyyy-MM-dd HH:mm:ss is used.
numberFormat:           Optional number format. If empty # is used.
skiplines:              Number of lines to skip. Default = 0.
divider:                Column divider. Default is semicolon
process(data, line):        Function called for each line in input stream. Required.
onerror(line, key, msg):    Optional function called on errors. Set to null to ignore erors

Column Definition (config.columns):

Each column is either a Sting or Object. If it is Object !=null the following properties are assumed:

key:    The column key
type:   optional - text|date|number|boolean - defaults to text

If it is String the format "key(type)" is allowed. Otherwise the String is taken as key with type=text as format.

null columns are ignored.

config.process(data, line):

This function is called for each csv line read in. The JavaScript object "data" carries the imported column values keyed by the keys defined in config.columns. Parameter "line" contains the current line number as integer value beginning with 1.

Sampe usages:

<tml:form id="import">
    <tml:input name="csv" type="file"/>
    <tml:button clickaction="import">Import ...</tml:button>
</tml:form>

<tml:action id="import">
    var filename = tmlform.csv;
    filename && AFW.Util.csvReader({

        columns: [
            "title", 
            {
                key: "created",
                type: "date"
            }, 
            null,   // ignore this columns
            "ean", 
            "price(number)" // key=price, type=number
        ],
        onerror: null,  // ignore errors
        process: function(data){
            for(let [key, value] in data)
                console.log(key, "=", value);
        }

    }).read(tmlform.getFile(filename))
</tml:action>