4
votes

Within my Java application I am creating new Google sheets as follows:

    Sheets service = new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();

    SpreadsheetProperties properties = new SpreadsheetProperties();
    properties.setTitle("Title");

    Spreadsheet export = new Spreadsheet();
    export.setProperties(properties);

    Spreadsheet response = service.spreadsheets().create(export).execute();

This works, and I can get the sheet ID in the response. Now I would like to know:

  1. As I am using Service account, I don't see who will be the user creating the spreadsheet.
  2. I would like to set permissions to "Anyone who has the link", but there seem to be no option for that.
1

1 Answers

1
votes

As I am using Service account, I don't see who will be the user creating the spreadsheet.

You can make use of "user" as type like:

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("[email protected]")
        .build();

But it really depends on your end goal. Here are the possible Types and Values.

user - emailAddress - Email address of a user. Example: [email protected]

group - emailAddress - Email address of a Google Group. Example: [email protected] domain-

domain - Domain name of Google Apps domain. Example: thecompany.com anyone - N/A The

anyone - permission does not require an emailAddress or domain field.

Check this SO thread for addtional info.

I would like to set permissions to "Anyone who has the link", but there seem to be no option for that.

Use "anyone" as user type which has been mentioned above. Then use "reader" as role.

private Permission insertPermission(Drive service, String fileId) throws Exception{
   Permission newPermission = new Permission();
   newPermission.setType("anyone");
   newPermission.setRole("reader");
   newPermission.setValue("");
   newPermission.setWithLink(true);
   return service.permissions().insert(fileId, newPermission).execute();
}

Check this helpful SO thread.