Google Java v4 API to read Google Sheets

Google have recently released V4 of their API, and this also applies to Google Sheets. There are various types of access/authorization available e.g. web server, client-side. However, there is also consideration given to service accounts.

Create a simple Google Sheet and add some cell data. Select the cells and create a range name.

The first step, towards reading this data, is to create a Google project account, at https://console.developers.google.com/permissions/serviceaccounts, using the menu at the top of the page. Use that project, to create a service account. It may be necessary to select a project, to view the required menu. Click on "create service account", and save the P12 file somewhere locally, as below

So, there is now a new project with a service account, as below.

In a new tab, navigate to https://console.developers.google.com/apis/library and the library of APIs should be visible. Under the "Google Apps API", select Sheets API and enable it.

Give the service account read-only access to the Google Sheet, using the service account id for the email address. Using the Java client jars at https://developers.google.com/api-client-library/java/google-api-java-client/download, it is now possible to write some Java code to read the sheet data.

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.ValueRange;

public class Test
{

    private static JsonFactory getJsonFactory()
    {
            return JacksonFactory.getDefaultInstance();  
    }
    
    private static HttpTransport getHttpTransport() 
       throws GeneralSecurityException, IOException
    {
            return GoogleNetHttpTransport.newTrustedTransport();
    }
    public static Credential getCredentials() 
        throws GeneralSecurityException, IOException
    {
        URL path = Test.class.getResource("xxx.p12");
        File p12 = new File(path.getFile());
        System.out.println(p12.getAbsoluteFile());
        List<String> SCOPES_ARRAY = 
                  Arrays.asList(SheetsScopes.SPREADSHEETS_READONLY);
        
        Credential credential = new GoogleCredential.Builder()
                    .setTransport(getHttpTransport())
                    .setJsonFactory(getJsonFactory())
                    .setServiceAccountId("your serviceaccount.com")
                    .setServiceAccountScopes(SCOPES_ARRAY)
                    .setServiceAccountPrivateKeyFromP12File(p12)                    
                    .build();
       
        return credential;                         
    }    

    public static List<List<Object>> getValues(String sheetName) 
        throws GeneralSecurityException, IOException
    {
        Credential credential = getCredentials();
        Sheets sheets = new Sheets.Builder(getHttpTransport(), 
                                           getJsonFactory(), 
                                           credential)
                                  .setApplicationName("your application")
                                  .build();
        String range = "range_name";

        ValueRange response = sheets.spreadsheets()
                                    .values()
                                    .get(sheetName, range)
                                    .execute();

        System.out.println(response.values().toString());
        return response.getValues();
    }
    
    public static void main(String[] args) 
         throws GeneralSecurityException, IOException
    {
        for (List<Object> row : getValues("sheet name")) {
            System.out.printf("%s, %s\n", row.get(0), row.get(1));
          }   
    }
}

 
  

And that's it.

I mentioned the range as "Sheet1!A1A6". no luck. 

Like
Reply

Saved me a lot of time to get my job done. Thanks!

Like
Reply

Thanks a lot for this document. It helps me a lot.

Like
Reply

To view or add a comment, sign in

More articles by syed shabbir

Others also viewed

Explore content categories