我开发了一个测试自动化框架,可以在excel表中为测试用例写入通过或失败值。我们已决定迁移到Google表格。
是否有人可以使用Google Sheet API V4提供样本Java代码以将数据写入Google表格?
我有一份表格文件,但目前尚不清楚。
谢谢。
答案 0 :(得分:4)
要write to a sheet,您需要电子表格ID,A1表示法中的范围以及您希望write在相应的请求正文对象中排列的数据。
要将数据写入单个范围,请使用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 = "<your service account email address>";
// Add requested scopes.
private final List<String> 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 = "/<your p12 file name>.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<SpreadsheetEntry> 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;
}
}
答案 1 :(得分:2)
请找到上述问题的答案:
0