python - 使用 gspread 获取所有谷歌表格的列表?

标签 python api google-sheets google-api gspread

目前我可以使用 gspread 连接并创建/共享电子表格。我还可以从所述电子表格中读取数据,但我必须按名称请求。有没有办法列出与正在使用的 OAuth 帐户共享的所有电子表格。

我可能不知道将与该帐户共享的电子表格的所有名称,因此如果可能的话,我希望以编程方式列出它们。

到目前为止,我所能做的就是按名称选择一张工作表。但我需要能够提取与我的 service_account 共享的所有工作表的列表。

到目前为止,我在网上找到的所有内容都与获取工作簿中的工作表列表有关,而不是与所有可用工作簿的列表有关。

欢迎提供文档,尽管到目前为止我发现的所有内容都没有帮助。

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import tkinter as tk


class Main(tk.Tk):
    def __init__(self):
        super().__init__()
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.geometry('1000x400')
        self.txt = tk.Text(self)
        self.txt.grid(row=0, column=0, sticky='nsew')
        self.scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
                      "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
        self.txt.insert('end', '{}\n'.format(self.scope))
        print('Scope: ', self.scope)
        self.after(2000, self.testing)

    def testing(self):
        creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', self.scope)
        client = gspread.authorize(creds)

        try:
            sh = client.create('Created By App')
            sh.share('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c4d087c8cacac6dcc7dde9dec6dbc2ccc4c8c0c587cac6c4" rel="noreferrer noopener nofollow">[email protected]</a>', perm_type='user', role='writer')

        except Exception as e:
            print('Error: ', e)

        try:
            print('Client: ', client)
            try:
                self.txt.insert('end', '{}\n'.format('Running: client.list_permissions("TestingSheet")'))
                self.txt.insert('end', '{}\n\n'.format(client.list_permissions("TestingSheet")))
            except Exception as e:
                self.txt.insert('end', 'Error: {}\n\n'.format(e))
                print('Error: ', e)
            try:
                self.txt.insert('end', '{}\n'.format('Running: client.list_spreadsheet_files()'))
                self.txt.insert('end', '{}\n\n'.format(client.list_spreadsheet_files()))
            except Exception as e:
                self.txt.insert('end', 'Error: {}\n\n'.format(e))
                print('Error: ', e)
            try:
                self.txt.insert('end', '{}\n'.format('Running: client.session()'))
                self.txt.insert('end', '{}\n\n'.format(client.session()))
            except Exception as e:
                self.txt.insert('end', 'Error: {}\n\n'.format(e))
                print('Error: ', e)

            # Find a workbook by name and open the first sheet
            # Make sure you use the right name here.
            sheet = client.open("TestingSheet").sheet1
            self.txt.insert('end', '{}\n\n'.format(sheet))
            print('Sheet: ', sheet)
            # Extract and print all of the values
            list_of_hashes = sheet.get_all_records()
            self.txt.insert('end', '{}\n\n'.format(list_of_hashes))
            print('list_of_hashes: ', list_of_hashes)
        except Exception as e:
            self.txt.insert('end', 'Error: {}\n\n'.format(e))
            print('Error: ', e)

creds.json 的格式如下:

{
  "type": "service_account",
  "project_id": "XXXXXXXXXXXXXXXXXXXXXXXX",
  "private_key_id": "XXXXXXXXXXXXXXXXXXXXXXXX",
  "private_key": "-----BEGIN PRIVATE KEY-----\nXXXXXXXXXXXXXXXXXXXXXXXX\n-----END PRIVATE KEY-----\n",
  "client_email": "project-service-account@XXXXXXXXXXXXXXXXXXXXXXXX.iam.gserviceaccount.com",
  "client_id": "XXXXXXXXXXXXXXXXXXXXXXXX",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/project-service-<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9e9c9c908a918bbfa7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7d1969e92d1988c9a8d89969c9a9e9c9c908a918bd19c9092" rel="noreferrer noopener nofollow">[email protected]</a>"}

最佳答案

这是可能的。

import gspread
gc = gspread.service_account('./creds.json')
def createNewSheetIfNotExist(title):
    if title not in [sh.title for sh in gc.openall()]:
        gc.create(title)
    print([sh.title for sh in gc.openall()])
    
createNewSheetIfNotExist('Test')
createNewSheetIfNotExist('Test')

多次运行该函数不会添加新工作表,因为它已在 gc.openall() 中找到了其标题。

gspread API Reference

关于python - 使用 gspread 获取所有谷歌表格的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67388393/

相关文章:

c++ - C++ 公共(public) API 的最佳实践是什么?

validation - 来自另一个 Google 表格的数据验证

python - 樱桃不关闭套接字

python - pandas 中 groupby 统计数据中的 NaN 值

python - 如何使 Jupyter Notebook 中的内联图更大?

python - 使用Spyder IDE : SyntaxError: 'continue' not properly in loop

javascript - FCKeditor JavaScript API 抛出 "Security error"代码 : "1000" when I attempt SetHTML()

javascript - 数据绑定(bind)剑道 ui 网格与外部 API

google-apps-script - 有没有办法在谷歌表格中点击鼠标放大图像?

google-sheets - 我从一个简单的查询中收到此消息(CANNOT_GROUP_WITHOUT_AGG)