使用pygsheets如何检测电子表格是否已经存在?

时间:2019-11-30 22:53:19

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

我使用pygsheets寻找一种好的方法来打开Goog​​le表格(按标题)(如果已存在),否则创建它。

与此同时,我还想让它对我自己和对世界其他地方都可以读写。

1 个答案:

答案 0 :(得分:0)

这就是这样做的:

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")