How do I create a Google Spreadsheet with a service account and share to other google users in java?

后端 未结 1 985
渐次进展
渐次进展 2020-12-07 23:23

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

1条回答
  •  执念已碎
    2020-12-08 00:03

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

    0 讨论(0)
提交回复
热议问题