Java Google Sheet API

Java Google Sheet API,第1张

完成本页其余部分描述的步骤,创建一个简单的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/

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/722034.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存