如何使用服务帐户创建Google电子表格并使用Java与其他Google用户共享?

2022-09-03 02:08:49

我有一个应用程序,我使用Google服务帐户从Analytics API收集有关我网站的大量信息。我的下一步是使用服务帐户创建一个电子表格,并与几个用户共享文档。

我已经在 https://developers.google.com/google-apps/spreadsheets/ 查看了文档,但我找不到有关服务帐户和共享文档的任何信息。

所以我的第一个问题是这可能吗?如果没有,我是否需要实现文档中例证的“使用我的个人帐户”?如果是,你能给我举个例子吗?

谢谢!


答案 1

这是可能的,请参阅下面的示例(该示例确实需要一些调整):

创建驱动器服务:

   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);

另请参阅此相关问题


答案 2

推荐