How do I create a Google Spreadsheet with a servic

2019-01-16 14:58发布

I have an application where I, with a Google Service Account, gather lots of information about my site from the Analytics API. My next step is to create a spreadsheet with the service account and share the document with a couple of users.

I have checked out the documentation at https://developers.google.com/google-apps/spreadsheets/ but I can't find anything there about service accounts and sharing the documents.

So my first question is this possible? If not do I need to implement the "use my personal account" as exemplified in the documentation? If yes could you please provide me with an example?

Thank you!

1条回答
劳资没心,怎么记你
2楼-- · 2019-01-16 15:51

It is possible, see the example below (the example does need a bit of tweaking):

Create the drive service:

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

Create the spreadsheet:

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

Create a spreadsheet service:

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

Retrieve the sheet:

SpreadsheetService s = googleConn.getSpreadSheetService();
String spreadsheetURL = "https://spreadsheets.google.com/feeds/spreadsheets/" + file.getId();
SpreadsheetEntry spreadsheet = s.getEntry(new URL(spreadsheetURL), SpreadsheetEntry.class);

Add the data:

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

Also, see this related question

查看更多
登录 后发表回答