Skip to content

Instantly share code, notes, and snippets.

@mogsdad
Created January 30, 2014 17:51
Show Gist options
  • Save mogsdad/8714493 to your computer and use it in GitHub Desktop.
Save mogsdad/8714493 to your computer and use it in GitHub Desktop.
Google Apps Script's Charts Service uses a DataTable object as the source data for visualizations and tables. There is a built-in method that can create a DataTable given a Spreadsheet Range, but if you have a javascript table or array that you want to visualize, you need to use the DataTableBuilder class' primitive methods. This function simpli…
/**
* Produce a dataTable object suitable for use with Charts, from
* an array of rows (such as you'd get from Range.getValues()).
* Assumes labels are in row 0, and the data types in row 1 are
* representative for the table.
*
* @param {Array} data Array of table rows
*
@ @returns {DataTable} Refer to GAS documentation
*/
function dataTableFromArray( data ) {
var dataTable = Charts.newDataTable();
for (var col=0; col<data[0].length; col++) {
var label = data[0][col];
var firstCell = data[1][col];
if (typeof firstCell == 'string')
dataTable.addColumn(Charts.ColumnType.STRING, label);
else
dataTable.addColumn(Charts.ColumnType.NUMBER, label);
}
for (var row = 1; row < data.length; row++) {
dataTable.addRow(data[row]);
}
return dataTable.build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment