【问题标题】:With pygsheets how to detect if a spreadsheet already exists?使用 pygsheets 如何检测电子表格是否已经存在?
【发布时间】:2019-11-30 22:53:19
【问题描述】:

使用 pygsheets,我正在寻找一种打开 Google 工作表(按标题)的好方法,如果它已经存在,则创建它。

同时,我还想在创建它时将其变为对自己进行 r/w,并在对世界其他地方进行 r/o。

【问题讨论】:

标签: python python-3.x google-sheets pygsheets


【解决方案1】:

这就是这样做的:

import pygsheets

creds_file = "/path/to/your_creds_file.json"

gc = pygsheets.authorize(service_file=creds_file)

sheet_title = "my_google_sheet"
# Try to open the Google sheet based on its title and if it fails, create it                                                                                                                                                                                                                                                          
try:
    sheet = gc.open(sheet_title)
    print(f"Opened spreadsheet with id:{sheet.id} and url:{sheet.url}")
except pygsheets.SpreadsheetNotFound as error:
    # Can't find it and so create it                                                                                                                                                                                                                                                                                                  
    res = gc.sheet.create(sheet_title)
    sheet_id = res['spreadsheetId']
    sheet = gc.open_by_key(sheet_id)
    print(f"Created spreadsheet with id:{sheet.id} and url:{sheet.url}")

    # Share with self to allow to write to it                                                                                                                                                                                                                                                                                         
    sheet.share('YOUR_EMAIL@gmail.com', role='writer', type='user')

    # Share to all for reading                                                                                                                                                                                                                                                                                                        
    sheet.share('', role='reader', type='anyone')

# Write something into it                                                                                                                                                                                                                                                                                                             
wks = sheet.sheet1
wks.update_value('A1', "something")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2017-07-11
    • 2022-12-06
    • 2015-12-09
    • 2020-02-27
    • 2012-09-24
    • 1970-01-01
    相关资源
    最近更新 更多