Ash*_*kar 0 java google-sheets google-spreadsheet-api google-sheets-api
我开发了一个测试自动化框架,目前在 excel 表中为测试用例编写通过或失败值。我们已决定迁移到 Google 表格。
任何人都可以提供示例 Java 代码以使用 Google Sheet API V4 将数据写入 Google Sheet?
我有一个看表文档,但不清楚。
谢谢你。
要 写入工作表,您需要电子表格 ID、A1 表示法中的范围以及您希望写入的数据,这些数据 排列在适当的请求正文对象中。
要将数据写入单个范围,请使用电子表格.value.update 请求:
PUT https://sheets.googleapis.com/v4/spreadsheets/spreadsheet_id/values/range?valueInputOption=valueInputOption
Run Code Online (Sandbox Code Playgroud)
如果你想写多个不连续的范围,你可以使用一个电子表格.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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17028 次 |
| 最近记录: |