python - 如何使用 Python 将 Google 表单链接到 Google Sheet?

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

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

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

问题是这样的:

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

这是我一直在使用的代码片段:

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 来做到这一点的方法,但此时任何事情都可以工作。任何帮助表示赞赏!谢谢!

最佳答案

使用 Google Drive API 与 oauth2clientgspread 直接更新现有电子表格。

  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有关这些功能以及其他几十个功能的完整详细信息。

关于python - 如何使用 Python 将 Google 表单链接到 Google Sheet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63226181/

相关文章:

python - 如何使用 Tensorflow 2/Keras 保存和继续训练具有多个模型部分的 GAN

python - 指定 python 版本时 pip 和 virtualenv 出现问题

image - 在谷歌电子表格中使图像可点击

javascript - 下载整个文件夹(google Drive api)

Django FileResponse - 如何加快文件下载速度

python - 如何将Python类对象列表继承到类中?

python - 在不知道全名的情况下在字典中查找键

javascript - 尝试将 Stripe API key 添加到 Google Apps 脚本中的 UrlFetchApp 时收到 401 'truncated server' 错误

arrays - 解释 ArrayFormula 扩展规则

android - 是否可以从 google drive API 获取上传文件的链接