【问题标题】:AttributeError: 'Spreadsheet' object has no attribute 'range'AttributeError:“电子表格”对象没有属性“范围”
【发布时间】:2016-05-18 07:36:34
【问题描述】:

您好 stackoverflow 社区, 我是 python 新手。我想使用 gspread 编辑谷歌电子表格。以下是我正在使用的代码:

import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials

json_key = json.load(open('My Project-f3f034c4a23f.json'))
scope = ['https://spreadsheets.google.com/feeds']

credentials = ServiceAccountCredentials.from_json_keyfile_name('My Project-f3f034c4a23f.json', scope)
gc = gspread.authorize(credentials)

worksheet = gc.open('Roposo')

worksheet.update_acell('B1', 'Gspread!')

我收到错误:

Traceback(最近一次调用最后一次): 文件“C:\Users\user\Desktop\Python\spreadsheet.py”,第 16 行,在 cell_list = worksheet.range('A1:C7') AttributeError:“电子表格”对象没有属性“范围”

请告诉一个合适的解决方案。

【问题讨论】:

    标签: python google-sheets gspread


    【解决方案1】:

    您的可变工作表是整个电子表格文档,而不是工作表。 你应该做类似的事情

    ss = gc.open('Roposo')
    ws = ss.worksheet('myWorksheet') 
    ws.update_acell('B1', 'Gspread !') 
    

    如果名为'myWorksheet' 的工作表已经存在。否则创建一个新的工作表:

    ss = gc.open('Roposo')
    ws = ss.add_worksheet('title', 100, 20) #title, row, col
    ws.update_acell('B1', 'Gspread !')
    

    API documentation 更详细地描述了SpreadsheetWorksheet 这两个对象。

    【讨论】:

    • 嗨 Jacques,您的答案在我创建新工作表时有效,但是当我使用此代码时出现以下错误:ss = gc.open('Roposo') ws = ss.get_worksheet('Aworksheet') ws.update_acell('B1', 'Gspread !') 错误:文件“C:\Users\user\Desktop\ Python\spreadsheet.py”,第 15 行,在 ws = ss.get_worksheet('Aworksheet') 文件“build\bdist.win32\egg\gspread\models.py”,第 154 行,在 get_worksheet 返回 self._sheet_list [index] 类型错误:列表索引必须是整数,而不是 str
    • 抱歉,get_worsheet 函数将整数索引作为唯一参数。使用worksheet 代替按标题查找。答案相应修改。
    • 感谢雅克的帮助
    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2021-07-05
    • 2012-12-01
    相关资源
    最近更新 更多