【问题标题】:insert multiple columns to google spread sheet api PYTHON向谷歌电子表格api PYTHON插入多列
【发布时间】:2017-06-02 11:09:41
【问题描述】:

我正在尝试使用他们在 python 中的 api 将多个列插入到谷歌电子表格中,现在我正在循环中执行此操作,就像这样:

index = 0
for a in myList:
   sheet.insert_row(a, index) 
   index += 1

如果我可以在一个电话中将整个列表发送到电子表格,或者比我的方法更好的方法,我会很高兴,谢谢。

【问题讨论】:

  • 不是您问题的真正答案,但我最近尝试了来自 Google 员工的 hyou (GitHub, PyPi, Documentation) 软件包,我发现它非常易于使用.
  • 嘿,谢谢,它是否支持在一个命令中发送所有列??如果是这样,请指出正确的方向,再次感谢您。
  • 在您调用 commit() 之前,该库不会发出任何 API 请求。因此,您可以更改行的值,然后调用 commit。查看示例here
  • 这有点复杂,我仍然需要循环来实现这一点并在每个循环中调用 commit .. 或者你能告诉我你是怎么做到的吗?
  • 是的,您需要一个循环,但是当您致电 Worksheet.commit() 时,所有更改都将在单个 batchUpdate 操作中发送。请参阅我的答案以获取代码示例。

标签: python api google-spreadsheet-api


【解决方案1】:

根据 cmets 的要求,我将发布一个示例,说明如何使用包 hyou 执行此操作:

import hyou


my_list = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
]

# Login to Google Spreadsheet with credentials
collection = hyou.login('/path/to/credentails.json')

# Open a spreadsheet by ID
spreadsheet = collection['1ZYeIFccacgHkL0TPfdgXiMfPCuEEWUtbhXvaB9HBDzQ']

# Open a worksheet in a spreadsheet by sheet name
worksheet = spreadsheet['Sheet1']

# Insert values from my_list
for row_index, row in enumerate(my_list):
    for col_index, value in enumerate(row):
        worksheet[row_index][col_index] = value

# Call Worksheet.commit() to apply changes, before this no request will
# be made to the API
worksheet.commit()

还可以查看 views 以读取/写入子范围。

【讨论】:

  • 没问题。转到浏览器中的电子表格,您可以从 URL https://docs.google.com/spreadsheets/d/<spreadsheet_id>/edit#gid=0 中提取它。例如。对于docs.google.com/spreadsheets/d/1ZYeIFccacgHkL0TPfdgXiMfPCuEEWUtbhXvaB9HBDzQ/edit#gid=0,ID 是1ZYeIFccacgHkL0TPfdgXiMfPCuEEWUtbhXvaB9HBDzQ