简体   繁体   中英

Google sheets python api not reading cells correctly

So, my problem is simple, when I read the cells I need in my script, the script for some reason says that a cell is empty when it is not, for example I always read cell "C4" but the script still says that it is empty even when it is not.

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))

Based on your code, you want to get the first sheet in your spreadsheet and check it's cell values depending on the declared words variable. But you are actually reading your fourth sheet in your spreadsheet.

Your code:

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

Selecting a Worksheet

  • You might want to reconsider using index when you are selecting your sheet, since there is a tendency that your spreadsheet might get re-arrange. The most safest way to select a worksheet is by its title/Sheet name

Select worksheet by index. Worksheet indexes start from zero:

worksheet = sh.get_worksheet(0)

Or by title:

worksheet = sh.worksheet("January")

Or the most common case: Sheet1:

worksheet = sh.sheet1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM