The above answer works great for YUI up to version 3.4. However, the data-table was refactored beginning with version 3.5. My converter encloses cell values in double quotes, escapes double quotes in cell values and handles one level of column nesting, if it exists.
Here is a fiddle that demonstrates my converter: http://jsfiddle.net/geocolumbus/AFB3h/3/
// Function to convert a DataTable with zero or one nested columns to CSV
function convertToCSV(myDataTable) {
var col,
colIndex = 0,
colKey,
rowString,
ret,
cell,
headerString = "";
while (col = myDataTable.getColumn(colIndex++)) {
if (col.children == null) {
headerString += '"' + col.key + '",';
} else {
Y.Array.each(col.children, function (child) {
headerString += '"' + child.key + '",';
});
}
}
ret = headerString.replace(/,$/, '\n');
Y.Array.each(myDataTable.data.toJSON(), function (item) {
colIndex = 0;
rowString = "";
while (col = myDataTable.getColumn(colIndex++)) {
if (col.children == null) {
cell = item[col.key].replace(/"/g, "\\\"");
rowString += '"' + cell + '",';
} else {
Y.Array.each(col.children, function (child) {
cell = item[child.key].replace(/"/g, "\\\"");
rowString += '"' + cell + '",';
});
}
}
ret += rowString.replace(/,$/, '') + "\n";
});
return ret;
}