我有一个应用程序,我使用 Google服务帐户,从Analytics API收集有关我网站的大量信息。 我的下一步是使用服务帐户创建电子表格 并与几个用户分享文档。
我已在https://developers.google.com/google-apps/spreadsheets/查看了文档,但我找不到有关服务帐户和共享文档的任何内容。
所以我的第一个问题是可能的吗? 如果不是,我需要实施文档中举例说明的“使用我的个人帐户”吗? 如果是的话,请你提供一个例子吗?
谢谢!
答案 0 :(得分:17)
有可能,请参阅下面的示例(该示例需要进行一些调整):
创建驱动器服务:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://www.googleapis.com/auth/drive")
.setServiceAccountPrivateKeyFromP12File(new File("path to the P12File"))
.setServiceAccountUser("user@domain.com")
.build();
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
创建电子表格:
com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File();
file.setTitle("test");
file.setMimeType("application/vnd.google-apps.spreadsheet");
Insert insert = this.drive.files().insert(file);
file = insert.execute();
创建电子表格服务:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://spreadsheets.google.com/feeds")
.setServiceAccountPrivateKeyFromP12File(new File("path to the P12File"))
.setServiceAccountUser("user@domain.com")
.build();
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setOAuth2Credentials(credential);
检索工作表:
SpreadsheetService s = googleConn.getSpreadSheetService();
String spreadsheetURL = "https://spreadsheets.google.com/feeds/spreadsheets/" + file.getId();
SpreadsheetEntry spreadsheet = s.getEntry(new URL(spreadsheetURL), SpreadsheetEntry.class);
添加数据:
WorksheetFeed worksheetFeed = s.getFeed(spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
WorksheetEntry worksheet = worksheets.get(0);
URL cellFeedUrl= worksheet.getCellFeedUrl ();
CellFeed cellFeed= s.getFeed (cellFeedUrl, CellFeed.class);
CellEntry cellEntry= new CellEntry (1, 1, "aa");
cellFeed.insert (cellEntry);
另请参阅此相关question