Skip to content

Instantly share code, notes, and snippets.

@pilate
Created December 14, 2011 16:52
Show Gist options
  • Save pilate/1477408 to your computer and use it in GitHub Desktop.
Save pilate/1477408 to your computer and use it in GitHub Desktop.
Extending the 'google.visualization.DataTable' prototype with toCSV
// Extend DataTable functionality to include toCSV
google.visualization.DataTable.prototype.toCSV = function () {
var dt_cols = this.getNumberOfColumns();
var dt_rows = this.getNumberOfRows();
var csv_cols = [];
var csv_out;
// Iterate columns
for (var i=0; i<dt_cols; i++) {
// Replace any commas in column labels
csv_cols.push(this.getColumnLabel(i).replace(/,/g,""));
}
// Create column row of CSV
csv_out = csv_cols.join(",")+"\r\n";
// Iterate rows
for (i=0; i<dt_rows; i++) {
var raw_col = [];
for (var j=0; j<dt_cols; j++) {
// Replace any commas in row values
raw_col.push(this.getFormattedValue(i, j, 'label').replace(/,/g,""));
}
// Add row to CSV text
csv_out += raw_col.join(",")+"\r\n";
}
return csv_out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment