我正在尝试学习如何使用谷歌数据API,我试图在已公开的谷歌电子表格中插入一行。电子表格的网址为:https://docs.google.com/spreadsheets/d/1thx0Mzts4rZ6Q7gLP_5zeXTmrOBMzsQtanJhBXg3er0/pubhtml
我正在使用的源代码是 -
import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.*;
import java.util.*;
public class GoogleDocs {
public static void main(String[] args)
throws AuthenticationException, MalformedURLException, IOException, ServiceException {
SpreadsheetService service = new SpreadsheetService("GoogleDocsUsingGdataApi");
URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/public/basic");
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
SpreadsheetEntry spreadsheet = spreadsheets.get(0);
System.out.println(spreadsheet.getTitle().getPlainText());
// Get the first worksheet of the first spreadsheet.
WorksheetFeed worksheetFeed = service.getFeed(spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
WorksheetEntry worksheet = worksheets.get(0);
// Fetch the list feed of the worksheet.
URL listFeedUrl = worksheet.getListFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
// Create a local representation of the new row.
ListEntry row = new ListEntry();
row.getCustomElements().setValueLocal("firstname", "Joe");
row.getCustomElements().setValueLocal("lastname", "Smith");
row.getCustomElements().setValueLocal("email", "joesmith@gmail.com");
// Send the new row to the API for insertion.
row = service.insert(listFeedUrl, row);
}
}
此代码未将任何数据插入电子表格。你能告诉我这段代码有什么不对吗?
答案 0 :(得分:0)
在未登录Google的浏览器中打开电子表格网址,您将看到您无法匿名编辑该表格。至少我不能。
Create a service account并使用它登录,然后您就可以编辑工作表了。
请参阅上面的链接,了解如何创建GoogleCredential
,然后使用凭据打开服务:
myService = new SpreadsheetService(appname);
myService.setOAuth2Credentials(credential);