python gspread 库只写入标记为 'sheet1' 的工作表

标签 python worksheet gspread

我的工作表名为“doc_name”,它有两个工作表,“sheet1”和“sheet2”。但是,我只能将数据写入标有“sheet1”的工作表吗?

这是限制还是我做错了什么?

这有效,

wks = gc.open("doc_name").sheet1

但这失败了,

wks = gc.open("doc_name").sheet2

给出这个错误,

AttributeError: 'Spreadsheet' 对象没有属性 'sheet2'

我也注意到这失败了,

wks = gc.open("doc_name").Sheet1

...我使用大写“S”的地方..只有当我指定小写时它才会写入。sheet1

如何在不编写代码的情况下写入工作表...wks = gc.open("doc_name").sheet1?

最佳答案

这是因为 gspread 只实现了 sheet1 来让您检索电子表格中的第一个工作表作为快捷方式

来自source code你可以看到 sheet1 的实现是使用 get_worksheet(0)

@property
def sheet1(self):
    """Shortcut property for getting the first worksheet."""
    return self.get_worksheet(0)

所以如果你想检索其他工作表,你需要使用其他方法,如:

1.将 index 指定为一个整数,表示从 0 开始打开工作表的位置:

wks = gc.open("doc_name").get_worksheet(index)

2.指定要作为字符串打开的工作表的标题:

wks = gc.open("doc_name").worksheet(title)

也就是说,在您的情况下,要获取 sheet2,您可能可以使用

wks = gc.open("doc_name").get_worksheet(1)

关于python gspread 库只写入标记为 'sheet1' 的工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33570749/

相关文章:

python PyQt : Is it possible to use QThread with a non-GUI program?

python - 在数据框中查找并替换半通用字符串?

vba - 工作表和模块之间的变量不合作

python - 使用 gspread python 在 Google Sheets 的最后一个填充行之后添加数据

google-apps-script - 使用 gspread 写入时出现 Google Sheets API 权限错误

python - 在 Python 中将字符串拆分为列表(但不分隔相邻数字)

python - 类型错误 : Only length-1 arrays can be converted to Python Scalars

c# - OleDB 和美元符号

excel - Excel 何时以及如何重新计算其公式?

python/gspread - 如何使用数据列表更新一系列单元格?