【问题标题】:Using Python to Create a New Google Sheet使用 Python 创建新的 Google 表格
【发布时间】:2021-08-05 15:07:08
【问题描述】:

背景

大家好...对 python 来说还是很新的。我在 Firefox (87.0) 中运行 Jupyter Notebook 的 Mac (Sierra) 上。我正在尝试使用我的 python 脚本来构建一个数据框,在我的个人 Google Drive 上的特定文件夹中创建一个新的 Google 工作表(一个新工作簿,而不是现有工作簿中的新工作表),然后将我的数据框架写入那个新的 Google 表格。

我的尝试

我已经能够让我的服务帐户打开现有的 Google 表格,然后使用如下代码进行读/写:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from gspread_dataframe import set_with_dataframe

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name(json_path, scope)
client = gspread.authorize(creds)
workbook = client.open_by_key(my_existing_google_sheet_key)

有大量关于如何从现有 Google 表格读取/写入的文档,但正如我所说,我想创建一个新的 Google 表格来写入。这出乎意料地难以找到。我确实找到的一个参考是this related post,但无法让 OP 的代码工作(什么是“发现”?)。我觉得我错过了一些明显的东西。

问题

  1. 如何使用 python 让我的服务帐户在我的个人 Google Drive 上的特定文件夹中创建一个新的 Google Sheet,以便我可以写入它?

【问题讨论】:

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


    【解决方案1】:

    我相信你的目标如下。

    • 您想使用服务帐户在您自己的 Google 云端硬盘的特定文件夹中创建新的 Google 电子表格。
    • 您希望使用 gspread 和 python 来实现此目的。

    修改点:

    当这些反映到你的脚本中时,它变成如下。

    修改脚本:

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    from gspread_dataframe import set_with_dataframe
    
    json_path = '###' # Please set the file for using service account.
    
    scope = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
    creds = ServiceAccountCredentials.from_json_keyfile_name(json_path, scope)
    client = gspread.authorize(creds)
    
    spreadsheetTitle = 'new spreadsheet title'
    folderId = '###' # Please set the folder ID of the folder in your Google Drive.
    
    workbook = client.create(spreadsheetTitle, folder_id=folderId)
    

    注意:

    • 在这种情况下,需要将您的 Google Drive 的特定文件夹与服务帐户的电子邮件共享。这样,可以将电子表格创建到具有服务帐户的文件夹中。请注意这一点。

    参考:

    【讨论】:

    • @Fist Pump Cat 现在,我注意到 Class Client 的 create 方法有一个参数,用于在创建新的电子表格时放入特定的文件夹。我为此道歉。使用它时,脚本会变得更简单。所以我更新了我的答案。你能确认一下吗?
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2016-02-15
    • 2014-08-28
    • 2020-07-22
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多