【问题标题】:Getting values from multiple google worksheets using single "gspread" command使用单个“gspread”命令从多个谷歌工作表中获取值
【发布时间】:2021-07-22 14:05:57
【问题描述】:

我一直在编写这段代码来访问一个名为“Classmates”的谷歌工作表和其中两个名为“School”和“Collage”的工作表,每个工作表都有文件句柄“ws1”和“ws2”。

import gspread
jf=gspread.service_account("E:\PyProj\Gsheets\creds.json")
wb=jf.open("Classmates")
ws1=wb.worksheet("School")
ws2=wb.worksheet("Collage")

inp=int(input("What data you want to get\t:"))
if inp==1:
    ws="ws1"
elif inp==2:
    ws="ws2"
else:
    print("Try again")
data=ws.get_all_values()        #line 14 with error
print(data)

现在我正在尝试根据选择从两张表中的任何一张中获取所有值。 它给出了以下错误

line 14, in <module>
data=ws.get_all_values()

AttributeError: 'str' object has no attribute 'get_all_values'

我不想编写单独的代码来获取值。 由于我使用的是 Gspread,所以请从 Gspread API 参考而不是 Google Sheets API 中提出解决方案。 谢谢你

【问题讨论】:

  • 出现错误时,ws 是一个字符串,因此没有名为 get_all_values 的属性。将 ws="ws1" 更改为 ws=ws1 并将 ws="ws2" 更改为 ws=ws2

标签: python python-3.x google-sheets attributeerror gspread


【解决方案1】:

好吧,我尝试了一种解决方法,它奏效了

import gspread
jf=gspread.service_account("E:\PyProj\Gsheets\creds.json")
wb=jf.open("Classmates")
def getvalue(sheetname):
    ws1=wb.worksheet(sheetname)
    lis_of_name=ws1.get_all_values()
    return lis_of_name
    
inp=int(input("What data you want to get\t:"))
if inp==1:
    data=getvalue("School")
elif inp==2:
    data=getvalue("Collage")
else:
    print("Try again")
print("BACK IN MAIN :-)")
print(data)

我没有将文件句柄名称保存在“ws”中,而是将工作表的名称作为 worksheet() 的参数发送。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多