FYI - this blog post is from a long time ago, and I think things have changed quite a bit. I'm leaving it here because some parts my still be useful, but definitely read the comments and don't expect it to work out of the box.
- James, 26 Nov 2013
(Update - see comment from Sean about this no longer working due to auth changes from Google)
I wanted to use data from a google docs spreadsheet in a project, and the sample code all talks about how to authenticate and get lists of documents for a user.
In my case, I already had a public document that I wanted to read.
You’ll want to read the doc
here first, but there were two gaps.
- It wasn’t straightforward (at least for me) to figure out exactly what the URL for a public spreadsheet should be (the doc concentrates on private documents, and assumes you’re going to be iterating through a list of available spreadsheets, not going straight to a specific one).
- It wasn’t clear which Java classes mapped to the URLs I had.
So here’s a very simple sample, reading data from
this public spreadsheet:
The output:
One
1
Two
2
Three
3
The code:
package com.banshee;
import java.io.IOException;
import java.net.URL;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CustomElementCollection;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.util.ServiceException;
public class SpreadsheetSucker {
public static void main(String[] args) {
SpreadsheetService service = new SpreadsheetService("com.banshee");
try {
// Notice that the url ends
// with default/public/values.
// That wasn't obvious (at least to me)
// from the documentation.
String urlString = "https://spreadsheets.google.com/feeds/list/0AsaDhyyXNaFSdDJ2VUxtVGVWN1Yza1loU1RPVVU3OFE/default/public/values";
// turn the string into a URL
URL url = new URL(urlString);
// You could substitute a cell feed here in place of
// the list feed
ListFeed feed = service.getFeed(url, ListFeed.class);
for (ListEntry entry : feed.getEntries()) {
CustomElementCollection elements = entry.getCustomElements();
String name = elements.getValue("name");
System.out.println(name);
String number = elements.getValue("Number");
System.out.println(number);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}