You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java实现Google SpreadSheet读取?附client_secret.json配置代码

Java读取Google SpreadSheet完整实现(基于OAuth2授权)

我来帮你补全这个读取Google SpreadSheet的Java代码实现,结合你已经下载的client_secret.json,完整的授权流程和读取逻辑如下:

第一步:确保依赖到位

首先要在你的项目中添加Google Sheets API和OAuth2相关的依赖,如果是Maven项目,在pom.xml中加入:

<dependencies>
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-sheets</artifactId>
        <version>v4-rev20240229-2.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-java6</artifactId>
        <version>1.34.1</version>
    </dependency>
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>1.34.1</version>
    </dependency>
</dependencies>

第二步:完整的授权与读取代码实现

你已经写了授权方法的开头,这里补全完整逻辑,包括令牌持久化(避免每次运行都要手动授权):

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.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.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class SpreadSheetReader {
    // 定义常量
    private static final String APPLICATION_NAME = "Google Sheets Reader";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    // 令牌存储目录,自动创建,用来保存授权后的令牌
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
    // 仅请求只读权限,如需修改可换成SheetsScopes.SPREADSHEETS
    private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "/client_secret.json";

    /**
     * 创建授权凭证
     */
    public static Credential authorize() throws IOException, GeneralSecurityException {
        // 加载客户端密钥(你下载的client_secret.json)
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, 
            new InputStreamReader(SpreadSheetReader.class.getResourceAsStream(CREDENTIALS_FILE_PATH)));

        // 构建授权流程,指定权限、令牌存储位置等
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline") // 离线访问,下次运行无需重新授权
            .build();

        // 启动本地服务器接收授权回调,端口用8888
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        // 触发授权请求,自动打开浏览器让用户登录授权
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    /**
     * 创建Sheets服务实例
     */
    public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
        Credential credential = authorize();
        return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
    }

    /**
     * 读取SpreadSheet数据的示例方法
     * @param spreadsheetId 你的SpreadSheet ID(从URL中获取,比如https://docs.google.com/spreadsheets/d/XXX/edit中的XXX)
     * @param range 要读取的范围,比如"A1:C5"或者"Sheet1!A:C"
     */
    public static void readSpreadSheet(String spreadsheetId, String range) throws IOException, GeneralSecurityException {
        Sheets service = getSheetsService();
        ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
        List<List<Object>> values = response.getValues();
        if (values == null || values.isEmpty()) {
            System.out.println("没有找到数据。");
        } else {
            System.out.println("读取到的数据:");
            for (List<Object> row : values) {
                // 打印每一行内容,可根据需求自定义数据处理逻辑
                System.out.println(String.join(", ", row.stream().map(Object::toString).toArray(String[]::new)));
            }
        }
    }

    // 测试主方法
    public static void main(String[] args) throws IOException, GeneralSecurityException {
        // 替换成你的SpreadSheet ID和要读取的范围
        String spreadsheetId = "你的SpreadSheet ID";
        String range = "Sheet1!A1:D10";
        readSpreadSheet(spreadsheetId, range);
    }
}

第三步:关键细节说明

  • 令牌存储:TOKENS_DIRECTORY_PATH指定的目录会保存授权后的令牌,第一次运行会打开浏览器让你登录Google账号授权,之后再运行就不需要重复授权了。
  • 权限范围:这里用的是SheetsScopes.SPREADSHEETS_READONLY,如果需要修改数据,可以换成SheetsScopes.SPREADSHEETS。
  • SpreadSheet ID:从SpreadSheet的URL中获取,比如https://docs.google.com/spreadsheets/d/abc123xyz/edit中的abc123xyz就是ID。
  • client_secret.json位置:要确保这个文件放在项目的资源目录下(比如Maven的src/main/resources),这样代码才能通过getResourceAsStream读取到。

运行注意事项

  1. 第一次运行时,程序会自动打开浏览器,跳转到Google的授权页面,你需要用拥有该SpreadSheet访问权限的账号登录,然后授权给你的应用。
  2. 如果遇到授权错误,检查client_secret.json是否正确,以及你的Google Cloud项目是否启用了Sheets API(需要在Google Cloud控制台中手动启用Sheets API服务)。

内容的提问来源于stack exchange,提问作者user2531569

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:38:59