I wrote some code to export a datasources.view() to a csv file for anyone interested.
/**
* Converts a datasource's view to CSV and saves it using data URI.
* Uses underscore for collection manipulation http://underscorejs.org/
* Uses moment.js for date parsing (you can change this if you would like)
* TODO save it using Downloadify to save the file name https://github.com/dcneiner/Downloadify
* @param {Array.<Object>} data The data to convert.
* @param {boolean} humanize If true, it will humanize the column header names.
* It will replace _ with a space and split CamelCase naming to have a space in between names -> Camel Case
* @param {Array.<String>} ignore Columns to ignore.
* @returns {string} The csv string.
*/
var
toCSV =
function
(data, fileName, humanize, ignore) {
var
csv =
''
;
if
(!ignore) {
ignore = [];
}
//ignore added datasource properties
ignore = _.union(ignore, [
"_events"
,
"idField"
,
"_defaultId"
,
"constructor"
,
"init"
,
"get"
,
"_set"
,
"wrap"
,
"bind"
,
"one"
,
"first"
,
"trigger"
,
"unbind"
,
"uid"
,
"dirty"
,
"id"
,
"parent"
]);
//add the header row
if
(data.length > 0) {
for
(
var
col
in
data[0]) {
//do not include inherited properties
if
(!data[0].hasOwnProperty(col) || _.include(ignore, col)) {
continue
;
}
if
(humanize) {
col = col.split(
'_'
).join(
' '
).replace(/([A-Z])/g,
' $1'
);
}
col = col.replace(/
"/g, '"
"');
csv +=
'"'
+ col +
'"'
;
if
(col != data[0].length - 1) {
csv +=
","
;
}
}
csv +=
"\n"
;
}
//add each row of data
for
(
var
row
in
data) {
for
(
var
col
in
data[row]) {
//do not include inherited properties
if
(!data[row].hasOwnProperty(col) || _.include(ignore, col)) {
continue
;
}
var
value = data[row][col];
if
(value ===
null
) {
value =
""
;
}
else
if
(value
instanceof
Date) {
value = moment(value).format(
"MM/D/YYYY"
);
}
else
{
value = value.toString();
}
value = value.replace(/
"/g, '"
"');
csv +=
'"'
+ value +
'"'
;
if
(col != data[row].length - 1) {
csv +=
","
;
}
}
csv +=
"\n"
;
}
//TODO replace with downloadify so we can get proper file naming
window.open(
"data:text/csv;charset=utf-8,"
+ escape(csv))
};
//toCSV(dataSource.view(), "FileName not used yet", true, ['IdColumnToIgnore', 'AnotherColumnToIgnore']);