Java Google Sheet API
Posted carl-zhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Google Sheet API相关的知识,希望对你有一定的参考价值。
完成本页其余部分描述的步骤,创建一个简单的Java命令行应用程序,向 Google Sheets API发出请求。
注意:访问 Google 开发者 需要科学上网
1、准备工作
要运行这个快速启动,您需要以下先决条件:
- Java 1.8 or greater.
- Gradle 2.3 or greater.(本文使用的 maven)
- 启用API的谷歌云平台项目。要创建项目并启用API,请参见 创建项目并启用API。
- 创建桌面应用程序的授权凭据。要了解如何为桌面应用程序创建凭据,请参见创建凭据。
- 一个 Google 账户
2、图形操作步骤
在上面给出了关键操作的地址,下面就把我的操作步骤截图一下。这样方便大家跟着操作。
2.1 创建项目
创建说明:https://developers.google.com/workspace/guides/create-project
2.2 API 设置
2.3 进行 API 激活
2.4 搜索 Google Sheet
2.5 激活 Google Sheet
2.6 创建凭据
创建 oauth 2.0 客户端 ID:
2.7 添加白名单
为这个应用添加白名单,后续访问 Google Sheet 页就是使用当前白名单用户创建的 Google Sheet 页。
2.8 创建 Google Sheet 页
创建一个 Google Sheet 页,然后把 Google Sheet Example 页面的数据 Copy 到我们创建的 Google Sheet 页面里面。
这样前期的准备工作就准备完了。
3、代码示例
在 Google 云平台控制台页面把 OAuth 2.0 客户端 ID
的凭证下载下来。
项目结构图:
代码如下:
SheetsQuickstart.java
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.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
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.ValueRange;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class SheetsQuickstart
private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException
// Load client secrets.
InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null)
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
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(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
/**
* Prints the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
public static void main(String... args) throws IOException, GeneralSecurityException
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
final String range = "Class Data!A2:E";
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values == null || values.isEmpty())
System.out.println("No data found.");
else
System.out.println("Name, Major");
for (List row : values)
// Print columns A and E, which correspond to indices 0 and 4.
System.out.printf("%s, %s\\n", row.get(0), row.get(4));
运行结果:
注意:在第一次运行的时候需要上面添加的白名单用户进行授权。授权成功之后,才能够对白名单用户拥有的 Google Sheet 页进行读取操作。
参考文章:
- https://blog.csdn.net/u013351145/article/details/121163296
- https://developers.google.com/sheets/api/quickstart/java
- https://stackoverflow.com/questions/65756266/error-403-access-denied-the-developer-hasn-t-given-you-access-to-this-app-despi
- https://console.cloud.google.com/
以上是关于Java Google Sheet API的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Google Sheets API python 将下拉列表添加到 google sheet
从 Google Sheet API v4 追加数据不再起作用
如何使用API编辑google sheet而不需要手动登录?