Writing Google App Script
Submitted by selvam on Sun, 12/18/2011 - 21:29
Google App script lets us add interesting features that can prove productive. I had a small work for a friend which involved generating custom graphical representation of the Income / Expense maintained with Google Spreadsheet. Though I could have used some implicit ways to achieve the same, but for the sake of extensibility, I decided to write an app script for the graph generation.
The spreadsheet columns look like this,
Date,Particulars,From/To,Deposits,Payments,Balance
Here are the steps to generate an Area graph,
1) Go to your Google spreadsheet, Tools > Script Editor.
2) Place this following code,
- function buildFromSpreadsheet(range){
-
var dataTable = Charts.newDataTable();
-
dataTable.addColumn(Charts.ColumnType.STRING, 'Date');
-
dataTable.addColumn(Charts.ColumnType.NUMBER, 'Payments');
-
dataTable.addColumn(Charts.ColumnType.NUMBER, 'Income');
-
var income = new Array();
-
var expense= new Array();
-
var x='';
-
var tmp ='';
-
for (var i=3; i < range.length; i++)
-
{
-
if(range[i][0].toString()!=''){
-
tmp = Utilities.formatDate(range[i][0],"GMT + 5 : 30", "MMM-yyyy");
-
if(tmp in income){
-
if(range[i][4].toString()!='')
-
income[tmp] = income[tmp] + range[i][4];
-
}
-
else{
-
if(range[i][4].toString()!='')
-
income[tmp] = range[i][4];
-
}
-
if(tmp in expense){
-
if(range[i][5].toString()!='')
-
expense[tmp] = expense[tmp] + range[i][5];
-
}
-
else{
-
if(range[i][5].toString()!='')
-
expense[tmp] = range[i][5];
-
}
-
}
-
}
-
for(var index in income) {
-
if(index in expense)
-
dataTable.addRow([index,expense[index],income[index]]);
-
else
-
dataTable.addRow([index,0,income[index]]);
-
}
-
dataTable.build();
-
return dataTable;
-
}
-
-
-
function doGet() {
-
var range = SpreadsheetApp.openById('SPREADSHEET_KEY')
-
.getSheetByName('SHEET_NAME').getDataRange().getValues()
-
var data = buildFromSpreadsheet(range);
-
var chart = Charts.newAreaChart()
-
.setDataTable(data)
-
.setTitle("Income/Expense")
-
.build();
-
var uiApp = UiApp.createApplication().setTitle("My Chart");
-
uiApp.add(chart);
-
return uiApp;
-
}
doGet() is the entry point which reads the spreadsheet data and sends it to buildFromSpreadsheet. buildFromSpreadsheet generates data suitable for area graph and returns back.The doGet then creates a new area chart and returns the UI application.
3) In the script window, select Share > Publish as Service. You can select suitable options and you will receive a URL which you can share with other people.
4) http://code.google.com/googleapps/appsscript/service_charts.html is the service page for charts.

