使用Google Sheet API V4将数据写入Google表格 – Java示例代码

我有一个开发的测试自动化框架,可以在excel表中为测试用例写入通过或失败值。 我们已决定迁移到Google表格。

任何人都可以提供一个示例Java代码,使用Google Sheet API V4将数据写入Google表格吗?

我有一个表格文件,但目前尚不清楚。

谢谢。

要写入工作表 ,您需要电子表格ID,A1表示法中的范围以及您希望在适当的请求正文对象中排列的数据。

要将数据写入单个范围,请使用spreadsheets.value.update请求:

PUT https://sheets.googleapis.com/v4/spreadsheets/spreadsheet_id/values/range?valueInputOption=valueInputOption 

如果要编写多个不连续范围,可以使用spreadsheets.value.batchUpdate请求:

 POST https://sheets.googleapis.com/v4/spreadsheets/spreadsheet_id/values:batchUpdate 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; } } 

请找到以上问题的答案:

 package com.googledoc; import com.google.api.client.auth.oauth2.Credential; importcom.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; 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.jackson2.JacksonFactory; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.api.services.sheets.v4.model.*; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.Sheets.Spreadsheets; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.mortbay.log.Log; public class SheetsQuickstart { /** 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.json"); /** 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. * * If modifying these scopes, delete your previously saved credentials * at ~/.credentials/sheets.googleapis.com-java-quickstart.json */ private static final List SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS); public static ValueRange response; public static UpdateValuesResponse request; public static void main (String[] args) throws Exception { //List> values = SheetsQuickstart.getResponse("BrowserSheet","A1","A").getValues (); SheetsQuickstart.setValue("BrowserSheet","A1","A"); } 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 = SheetsQuickstart.class.getResourceAsStream("/resources/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 ValueRange getResponse(String SheetName,String RowStart, String RowEnd) throws IOException{ // Build a new authorized API client service. Sheets service = getSheetsService(); // Prints the names and majors of students in a sample spreadsheet: String spreadsheetId = "1234"; String range = SheetName+"!"+RowStart+":"+RowEnd; response = service.spreadsheets().values() .get(spreadsheetId, range).execute (); return response; } public static void setValue(String SheetName,String RowStart, String RowEnd) throws IOException{ // Build a new authorized API client service. Sheets service = getSheetsService(); // Prints the names and majors of students in a sample spreadsheet: String spreadsheetId = "1234"; String range = RowStart+":"+RowEnd; List> arrData = getData(); ValueRange oRange = new ValueRange(); oRange.setRange(range); // I NEED THE NUMBER OF THE LAST ROW oRange.setValues(arrData); List oList = new ArrayList<>(); oList.add(oRange); BatchUpdateValuesRequest oRequest = new BatchUpdateValuesRequest(); oRequest.setValueInputOption("RAW"); oRequest.setData(oList); BatchUpdateValuesResponse oResp1 = service.spreadsheets().values().batchUpdate(spreadsheetId, oRequest).execute(); // service.spreadsheets().values().update (spreadsheetId, range,) ; //return request; } public static List> getData () { List data1 = new ArrayList(); data1.add ("Ashwin"); List> data = new ArrayList>(); data.add (data1); return data; } }