user3672549
user3672549

Reputation: 31

openpyxl TypeError: string indices must be integers

import openpyxl, os 

cwd = os.getcwd()
print(cwd)

wb = openpyxl.load_workbook('Hello.xlsx')
print (type(wb))

sheetNames = wb.sheetnames
print(sheetNames[1])

sheet0 = sheetNames[0]
print (sheet0['A1']) <--TypeError: string indices must be integers

I have tried to use .value at the end too. The cell contains the number 55 in it. I am new to python so please help. Also if anyone has a good place for resources on excel and python that would be helpful. openpyxl seems to be the newest one so I am trying to use this but the documentation is poor.

Upvotes: 1

Views: 2493

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

You are getting the error TypeError: string indices must be integers as sheet0 is in fact a string (not the worksheet itself).

wb.sheetnames gives you a list of all of the worksheet names, e.g.

['Sheet 1', 'Sheet 2', 'Sheet 3']

So sheetNames[0] would give you the first sheet name Sheet 1 as a string.

To work with the data you need to first open the worksheet using the required sheet name.

You can also use wb.active to get the first worksheet object i.e. Sheet 1 to avoid the need to use wb.sheetnames:

import openpyxl

wb = openpyxl.load_workbook('Hello.xlsx')
ws = wb.active
print(ws['A1'].value)

To get the corresponding worksheet object you would use:

ws = wb[wb.sheetnames[0]]
print(ws['A1'].value)

Upvotes: 1

quantik
quantik

Reputation: 816

sheetname0 is the name for the first sheet. So what you're doing when you run sheetname0['A1'] is you're trying to access element A1 of a string - which doesn't make sense. If you wish you access the cell A1 of that sheet you must first access that sheet object.

ws = wb[sheetNames[0]]

Now that you have the sheet you can access the cell:

print(ws['A1'])

Also a general tip for Python considering you said you're new to it it's generally recommended you use snake_case for variable names.

Upvotes: 2

Related Questions