Skip to content

Instantly share code, notes, and snippets.

@volkov
Created November 22, 2017 22:40
Show Gist options
  • Save volkov/5048c20b6cb55b7994b726010be187f7 to your computer and use it in GitHub Desktop.
Save volkov/5048c20b6cb55b7994b726010be187f7 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
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.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.*;
import static java.util.Collections.singletonList;
public class Quickstart {
/**
* Application name.
*/
private static final String APPLICATION_NAME =
"Google Sheets API Java Quickstart";
/**
* Directory to store user credentials for this application.
*/
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/sheets.googleapis.com-java-quickstart");
/**
* Global instance of the {@link FileDataStoreFactory}.
*/
private static FileDataStoreFactory DATA_STORE_FACTORY;
/**
* Global instance of the JSON factory.
*/
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/**
* Global instance of the HTTP transport.
*/
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the scopes required by this quickstart.
* <p>
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/sheets.googleapis.com-java-quickstart
*/
private static final List<String> SCOPES =
Arrays.asList(SheetsScopes.SPREADSHEETS);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
Quickstart.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Sheets API client service.
*
* @return an authorized Sheets API client service
* @throws IOException
*/
public static Sheets getSheetsService() throws IOException {
Credential credential = authorize();
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Sheets service = getSheetsService();
String id = "1C87GjgieW3v_NCDBELE8wYq5OHblcUsEB8w5k0MZZG0";
Sheets.Spreadsheets.Get request = service.spreadsheets().get(id);
request.setRanges(singletonList("A1:1"));
request.setIncludeGridData(true);
Spreadsheet response = request.execute();
// TODO: Change code below to process the `response` object:
System.out.println(response);
Sheet sheet = response.getSheets().get(0);
System.out.println(sheet);
List<GridData> dataList = sheet.getData();
GridData data = dataList.get(0);
System.out.println(data);
List<RowData> rowDataList = data.getRowData();
RowData rowData = rowDataList.get(0);
System.out.println(rowData);
List<CellData> cells = rowData.getValues();
CellData cellData = cells.get(0);
System.out.println(cellData);
System.out.println(cellData.getEffectiveFormat().getBackgroundColor());
UpdateCellsRequest updateCellsRequest = new UpdateCellsRequest();
updateCellsRequest.setRows(singletonList(new RowData().setValues(
singletonList(cellData.setUserEnteredFormat(new CellFormat().setBackgroundColor(new Color().setBlue(1.0f)))))));
updateCellsRequest.setRange(new GridRange().setStartRowIndex(0).setEndRowIndex(1).setStartColumnIndex(0).setEndColumnIndex(1));
updateCellsRequest.setFields("*");
Sheets.Spreadsheets.BatchUpdate batchUpdate = service.spreadsheets().batchUpdate(id, new BatchUpdateSpreadsheetRequest().setRequests(singletonList(
new Request().setUpdateCells(updateCellsRequest))));
BatchUpdateSpreadsheetResponse cellUpdateResponse = batchUpdate.execute();
System.out.println(cellUpdateResponse);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment