CSV
Generating a CSV String
Format
CSV.stringify(source, options);
source
One of:
Array
Matrix (array of arrays)
options
(Optional)
Object with the following properties:
heading
: Array of column headings. Usenull
to generate a CSV file without a header row.delimiter
: Character to separate columns with.
Defaults to ,
Returns: the generated CSV as a string.
Examples
var mx = [['Cell Phone', 'Black'], ['Computer','Red']];
var csv_file = CSV.stringify(mx, {heading: ['Type', 'Color']});
In this case, csv_file
is
Type,Color
Cell Phone,Black
Computer,Red
Suppose we have an asset
data model object with (amongst others) name
and cost
as fields, and we want to generate CSV for all assets and their names and costs:
var allAssets = DB.asset.all().toArray();
var myMx = allAssets.map(function(asset) {
return [asset.name, asset.cost];
});
var csv = CSV.stringify(myMx, {heading: ['Name', 'Cost']});
Parsing a CSV String
Format
CSV.parse(source, options);
source
String
options
(Optional)
Object with the following properties:
delimiter
: Character to separate columns with. If no delimiter
is specified, the library detects and uses the appropriate one
Returns: the parsed CSV as an array of arrays.
Example
Assume csv_file
's content is:
Type,Color
Cell Phone,Black
Computer,Red
<!-- In the View XML -->
<var name="csv_file" type="attachment" media="text/csv" />
<capture-file bind="csv_file" required="false" />
var csvFileContent = view.csv_file.toText();
var parsed = CSV.parse(csvFileContent);
// Starting at 1 since the heading is in position 0
for (var i = 1; i < parsed.length; i++) {
var item = parsed[i];
var newAsset = DB.asset.create({
type: item[0],
color: item[1]
});
newAsset.save();
}
Last updated