【问题标题】:Get list of all google sheets using gspread?使用 gspread 获取所有谷歌表格的列表?
【发布时间】:2021-05-04 16:13:12
【问题描述】:

目前我可以使用 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('my.account@workemail.com', 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-account@XXXXXXXXXXXXXXXXXXXXXXXX.iam.gserviceaccount.com"}

【问题讨论】:

    标签: python api google-sheets google-api gspread


    【解决方案1】:

    有可能。

    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

    【讨论】:

      【解决方案2】:

      无法使用Gspread 列出所有共享的 Google 表格文件。由于它使用Google Sheets API v4,Sheets API 中没有现有方法可以列出驱动器中的 Google Sheets 文件。

      您需要使用Drive API 搜索使用files.list 与查询字符串q="mimeType='application/vnd.google-apps.spreadsheet' and sharedWithMe" 共享到您的服务帐户的Google 表格文件

      您的files.list 请求将返回files 列表,其中包含文件名及其文件ID。然后您可以使用 gspread 读取/修改您的 Google 表格文件。

      使用 API Explorer 的示例响应:

      {
       "kind": "drive#fileList",
       "incompleteSearch": false,
       "files": [
        {
         "kind": "drive#file",
         "id": "1wXCD1SaujjD46NM7NFpP8jrqL_xxxxx",
         "name": "File1",
         "mimeType": "application/vnd.google-apps.spreadsheet"
        },
        {
         "kind": "drive#file",
         "id": "1Bm7bFs8SveQt75geOGjDAmOgfxxxxx",
         "name": "File2",
         "mimeType": "application/vnd.google-apps.spreadsheet"
        }]
      }
      

      您可以查看以下关于如何在 Python 中设置和使用 Drive API 的参考资料:

      【讨论】:

      • 谢谢。这听起来很有希望。当我有机会时,我将不得不对此进行测试。确认后,我将更新接受的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多