[英]Get list of all google sheets using gspread?
目前我可以使用 gspread 連接並創建/共享電子表格。 我也可以從所述電子表格中讀取數據,但我必須按名稱請求它。 有沒有辦法列出與正在使用的 OAuth 帳戶共享的所有電子表格。
我可能不知道將與帳戶共享的電子表格的所有名稱,因此我希望盡可能以編程方式列出它們。
到目前為止,我所能做的就是 select 一張紙的名字。 但我需要能夠提取與我的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"}
無法使用Gspread列出所有共享的 Google 表格文件。 由於它使用Google 表格 API v4 ,因此表格 API 中沒有現有方法可以列出驅動器中的 Google 表格文件。
您需要使用Drive API使用帶有查詢字符串q="mimeType='application/vnd.google-apps.spreadsheet' and sharedWithMe"
搜索與您的服務帳戶共享的 Google 表格文件
您的files.list請求將返回一個文件列表,其中包含文件名及其文件 ID。 然后您可以使用 gspread 讀取/修改您的 Google 表格文件。
{
"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 中設置和使用驅動器 API 的參考資料:
有可能的。
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')
多次運行 function 不會添加新工作表,因為它在gc.openall()
中找到了標題。
如果目標是獲取工作簿名稱列表,則可以執行以下操作:
import gspread
gc = gspread.service_account("./creds.json")
workbooks = [file["name"] for file in gc.list_all_spreadsheets()]
gspread 的Client
object 的gc
實例的.list_all_spreadsheets
方法返回一個字典列表,其中包含與service account
共享的每個電子表格的信息。
如果我們的服務帳戶已共享給 3 個不同的電子表格,“工作簿 1”、“工作簿 2”和“工作簿 3”,則此方法將返回以下內容。
[{'kind': 'drive#file',
'id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'name': 'Workbook 1',
'mimeType': 'application/vnd.google-apps.spreadsheet'},
{'kind': 'drive#file',
'id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'name': 'Workbook 2',
'mimeType': 'application/vnd.google-apps.spreadsheet'},
{'kind': 'drive#file',
'id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'name': 'Workbook 3',
'mimeType': 'application/vnd.google-apps.spreadsheet'}]
我決定使用列表理解來遍歷這些字典。 有意者go以另一種方式了解此步驟。 如果以上是gc.list_all_spreadsheets()
的結果,那么workbooks
將是
['Workbook 1', 'Workbook 2', 'Workbook 3']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.