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

React中通过OAuth2令牌获取Google Drive表格名称列表

获取关联谷歌账户的所有谷歌表格名称

我已完成OAuth2客户端ID配置,在Google Cloud Console启用了Google Drive API,应用中点击按钮可打开谷歌登录面板,选择账户后能获取用户资料详情。现在需要获取该账户下的所有谷歌表格名称,求可行方案。

原授权代码如下:

const HomePage = () => {
    const googleClientID = 'xxxsxxxx-xxxxxxdfdfdxxxxxx2.apps.googleusercontent.com'

    const googleSuccess = async (res) => {
        console.log("googleSuccess")
        console.log(res)
    }

    const googleError = (error) => {
        console.log(error);
        alert('Google Sign In was unsuccessful. Try again later');
    }

    useEffect(() => {
        function start() {
            gapi.client.init({
                clientId: googleClientID,
                scope: ['https://www.googleapis.com/auth/drive', 'profile'],
            });
        }

        gapi.load('client:auth2', start);
    }, []);

    return (
        <GoogleLogin
            clientId={googleClientID}
            render={(renderProps) => (
                <Button style={{ backgroundColor: "blue", width: "400px" }}
                    fullWidth onClick={renderProps.onClick}
                    disabled={renderProps.disabled} startIcon={<Icon />} variant="contained">
                    Add Subscription by Google Sign In
                </Button>
            )}
            onSuccess={googleSuccess}
            onFailure={googleError}
            cookiePolicy="single_host_origin"
        />
    )
}

export default HomePage;

解决方案

通过调用Google Drive API的Files.list接口,过滤出谷歌表格类型的文件并提取名称,以下是修改后的完整代码:

import { useState } from 'react';
import { GoogleLogin } from 'react-google-login';
import Button from '@mui/material/Button';
import Icon from '@mui/icons-material/Google';

const HomePage = () => {
    const googleClientID = 'xxxsxxxx-xxxxxxdfdfdxxxxxx2.apps.googleusercontent.com'
    const [spreadsheets, setSpreadsheets] = useState([]);

    const googleSuccess = async (res) => {
        console.log("googleSuccess", res);
        // 加载Drive API客户端
        await gapi.client.load('drive', 'v3');
        try {
            // 查询所有谷歌表格
            const response = await gapi.client.drive.files.list({
                q: "mimeType='application/vnd.google-apps.spreadsheet'",
                fields: "files(id, name)", // 仅返回需要的字段,减小响应体积
                pageSize: 100 // 单次查询最大数量,可按需调整
            });
            const sheets = response.result.files;
            setSpreadsheets(sheets);
            console.log("获取到的表格列表:", sheets);
        } catch (error) {
            console.error("获取表格列表失败:", error);
            alert('获取表格列表失败,请稍后重试');
        }
    }

    const googleError = (error) => {
        console.log(error);
        alert('Google Sign In was unsuccessful. Try again later');
    }

    useEffect(() => {
        function start() {
            gapi.client.init({
                clientId: googleClientID,
                scope: ['https://www.googleapis.com/auth/drive.readonly', 'profile'], // 使用只读权限,更安全
            });
        }

        gapi.load('client:auth2', start);
    }, []);

    return (
        <div>
            <GoogleLogin
                clientId={googleClientID}
                render={(renderProps) => (
                    <Button style={{ backgroundColor: "blue", width: "400px" }}
                        fullWidth onClick={renderProps.onClick}
                        disabled={renderProps.disabled} startIcon={<Icon />} variant="contained">
                        Add Subscription by Google Sign In
                    </Button>
                )}
                onSuccess={googleSuccess}
                onFailure={googleError}
                cookiePolicy="single_host_origin"
            />
            {/* 渲染获取到的表格列表 */}
            {spreadsheets.length > 0 && (
                <div style={{ marginTop: 20 }}>
                    <h3>账户下的谷歌表格:</h3>
                    <ul>
                        {spreadsheets.map(sheet => (
                            <li key={sheet.id}>{sheet.name}</li>
                        ))}
                    </ul>
                </div>
            )}
        </div>
    )
}

export default HomePage;

关键说明

  • 权限优化:将原drive权限改为drive.readonly,遵循最小权限原则,降低应用风险。
  • API过滤逻辑:通过q参数指定MIME类型为application/vnd.google-apps.spreadsheet,确保只返回谷歌表格文件。
  • 分页处理:若账户下表格数量超过pageSize,需通过pageToken参数实现分页查询,可根据需求扩展该逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:05:23