【问题标题】:How to link a Google Form to a Google Sheet using Python?如何使用 Python 将 Google 表单链接到 Google 表格?
【发布时间】:2020-08-03 08:34:19
【问题描述】:

这是我的设置和我想要完成的任务:

  • 我目前设置了一个 Google 表单供用户提交信息,然后将其登录到 Google 表格中。
  • 然后,我使用 PyDrive 将 Google 表格的内容保存为 csv。
  • Pandas 然后读取该 csv,并根据特定标准删除 csv 中的数据。
  • 之后,我使用 PyDrive 将“固定”的 csv 重新上传到 Google 工作表,而不是旧的。

问题来了:

每当我这样做时,它都会终止 Google 表格和 Google 表单之间的链接。有什么方法可以保留此链接或重新链接表单和工作表?

这是我一直在玩的代码的 sn-p:

submissions_data = drive.CreateFile({'id': ext['SUBMISSIONS_ID']})
submissions_data.GetContentFile("data.csv", mimetype = "text/csv")
df = pd.read_csv("data.csv")
df.drop([0],inplace=True)
df.to_csv("data.csv", index=False)
submissions_data.SetContentFile("data.csv")`

最好,我想找到一种使用 PyDrive 的方法,但此时任何方法都可以。任何帮助表示赞赏!谢谢!

【问题讨论】:

  • 您是在创建新文件而不是更新现有文件吗?
  • @DaImTo 我确定我是,但我认为这是根据PyDrive's documentation更新文件最接近的方法

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


【解决方案1】:

使用带有 oauth2client 和 gspread 的 Google Drive API 直接更新现有的电子表格。

  1. 转到Google APIs Console。创建一个新项目。单击启用 API。
  2. 启用Google Drive API。创建凭据 供 Web 服务器访问应用程序数据。
  3. 为服务帐户命名并授予它编辑者的项目角色。
  4. 下载 JSON 文件。
  5. 将 JSON 文件复制到您的代码目录并将其重命名为 client_secret.json
  6. 在 client_secret.json 中找到 client_email。返回您的电子表格,单击右上角的共享按钮,然后将客户电子邮件粘贴到人员字段中以授予其编辑权限。点击发送。
pip install gspread oauth2client
#spreadsheet.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials


# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds =   ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Copy of Legislators 2017").sheet1

# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

您可以通过更改特定单元格来写入电子表格:

sheet.update_cell(1, 1, "I just wrote to a spreadsheet using Python!")

或者您可以在电子表格中插入一行:

row = ["I'm","inserting","a","row","into","a,","Spreadsheet","with","Python"]
index = 1
sheet.insert_row(row, index)

查看gspread API reference 以获取有关这些功能以及其他几十个功能的完整详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多