Java to Google Spreadsheet

前端 未结 5 1957
谎友^
谎友^ 2021-02-06 07:59

I was trying to do programming using Java to connect to Google Spreadsheet to do data retrieval or modifying data in the cells.

My Google spreadsheet link is https://doc

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-06 08:55

    You are getting the redirect because accessing your spreadsheet requires that you authenticate first. Google Sheets is using the old gdata API, but requires that you authenticate using OAuth 2.0. Therefore you will need to import both the gdata and Google API libraries as shown below:

    
        
            com.google.gdata
            core
            1.47.1
        
        
            com.google.api-client
            google-api-client-java6
            1.20.0
        
    
    

    The code below shows how you can authenticate with Google using OAuth. You will need to follow the instructions for creating a service account and downloading the P12 key first. After creating your service account, copy the email address into the CLIENT_ID field below, add your P12 file to your classpath and chante P12FILE to point to your P12 file.

    I was able to get this working with the following SPREADSHEET_FEED_URL "https://spreadsheets.google.com/feeds/worksheets/:worksheetId/private/basic" where ":worksheetId" is your worksheet Id. This is slightly different than the one you were using.

    Be sure to make sure that your service account has permission to read or write to the spreadsheet by sharing it with the service account email address first.

    public class GoogleSheetsApiTest {
    
    // Generate a service account and P12 key:
    // https://developers.google.com/identity/protocols/OAuth2ServiceAccount
    private final String CLIENT_ID = "";
    // Add requested scopes.
    private final List SCOPES = Arrays
            .asList("https://spreadsheets.google.com/feeds");
    // The name of the p12 file you created when obtaining the service account
    private final String P12FILE = "/.p12";
    
    
    @Test
    public void testConnectToSpreadSheet() throws GeneralSecurityException,
            IOException, ServiceException, URISyntaxException {
    
        SpreadsheetService service = new SpreadsheetService(
                "google-spreadsheet");
        GoogleCredential credential = getCredentials();
        service.setOAuth2Credentials(credential);
    
        URL SPREADSHEET_FEED_URL = new URL(
                "https://spreadsheets.google.com/feeds/worksheets/1UXoGD2gowxZ2TY3gooI9y7rwWTPBOA0dnkeNYwUqQRA/private/basic");
        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
                SpreadsheetFeed.class);
        List spreadsheets = feed.getEntries();
    
        if (spreadsheets.size() == 0) {
            // // TODO: There were no spreadsheets, act accordingly.
        }
        //
        SpreadsheetEntry spreadsheet = spreadsheets.get(0);
        System.out.println(spreadsheet.getTitle().getPlainText());
    
    }
    
    private GoogleCredential getCredentials() throws GeneralSecurityException,
            IOException, URISyntaxException {
        JacksonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        HttpTransport httpTransport = GoogleNetHttpTransport
                .newTrustedTransport();
    
        URL fileUrl = this.getClass().getResource(P12FILE);
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(CLIENT_ID)
                .setServiceAccountPrivateKeyFromP12File(
                        new File(fileUrl.toURI()))
                .setServiceAccountScopes(SCOPES).build();
    
        return credential;
    }
    
    }
    

提交回复
热议问题