【问题标题】:Google sheets python api not reading cells correctly谷歌表python api没有正确读取单元格
【发布时间】:2021-03-02 10:52:50
【问题描述】:

所以,我的问题很简单,当我在脚本中读取我需要的单元格时,脚本出于某种原因说一个单元格是空的,而实际上它不是,例如我总是读取单元格“C4”但脚本仍然说它是空的,即使它不是。

import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)

# get the instance of the Spreadsheet
sheet = client.open('Copy of Event Organizer')

# get the first sheet of the Spreadsheet
sheet_instance = sheet.get_worksheet(3)

words = ["C4", "C5", "C7", "C9", "C11", "C13", "C15", "C17", "C19", "C21", "C23", "C25"]
values = [1012, 12317, 1120, 1345, 134, 1120, 1420, 5, 531, 220, 15, 2354]

len_list = []
for i, word in enumerate(words):
    try:
        len_list.append(len(sheet_instance.acell(word).value))

    except:
        len_list.append(0)
    len_list[i] = len_list[i] * values[i]

print(len_list)
print(sum(len_list))
sheet_instance.update_acell("C29", sum(len_list))

【问题讨论】:

    标签: python google-sheets google-cloud-platform google-sheets-api


    【解决方案1】:

    根据您的代码,您希望获取电子表格中的第一张工作表并根据声明的 words 变量检查其单元格值。但您实际上是在电子表格中阅读您的fourth sheet

    您的代码:

    # get the first sheet of the Spreadsheet
    sheet_instance = sheet.get_worksheet(3)
    

    Selecting a Worksheet

    • 您可能希望在选择工作表时重新考虑使用索引,因为您的电子表格可能会重新排列。选择工作表最安全的方法是通过其title/Sheet name

    按索引选择工作表。工作表索引从零开始:

    worksheet = sh.get_worksheet(0)
    

    或按标题:

    worksheet = sh.worksheet("January")
    

    或者最常见的情况:Sheet1:

    worksheet = sh.sheet1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多