1

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

同时,我也想在创建它时让它对我自己进行 r/w,对世界其他地方进行 r/o。

4

1 回答 1

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")
于 2019-11-30T22:53:19.207 回答