Question

I've been using the openpyxl module to do some processing on some .xlsx files. I've been trying to figure out how to iterate over sheets in a workbook. I'm not sure if I can get it figured out. I've tried the 2 codes below which both return empty results. My .xlsx file has about 20 sheets, so something should return.

The one thing I couldn't find on the internet, is how to set a workbook to an actual workbook. Usually I am writing to a workbook, so I just initialize it by setting a variable to en empty workbook workbook = Workbook() but in this case, I am unsure if I can open a workbook by doing workbook = Workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx")

If anyone can identify what it is I am doing wrong, I would appreciate it.

Here is my code:

workbook = Workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx")

for sheet in workbook.worksheets:
    print sheet

# or

for sheet in workbook.worksheets:
    print sheet.title
Was it helpful?

Solution

Open the workbook via load_workbook() and iterate over worksheets:

from openpyxl import load_workbook

wb = load_workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx")

for sheet in wb.worksheets:
    print(sheet)

OTHER TIPS

Here's one if you need active worksheets for your code

for sheet in wb:
    ws = wb[sheet]
    print('Now in sheet: ' + ws.title)

To print titles of all sheets in a workbook:

from openpyxl import load_workbook

wb = load_workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx")
print(wb.sheetnames)

I struggled a bit with the whole "workbook.active" and didn't know how to get around it so I tried a little bit of everything and here is what worked well for me!

for sheet in workbook.sheetnames[2:len(workbook.sheetnames)]:
     ws = workbook[value]
     for val in ws.iter_rows(min_row=11, max_row=21, min_col=2, max_col=10, values_only=True):
          print(str(sheet) + " " + str(val))

This will print the sheet name starting with the third sheet, since that's what I needed, as well as all the cell values referenced. The only other thing is this prints a list and if you want to iterate through each value and pull out "0s" or "None" values, then you'll need another loop. Hope this helps whoever else is looking!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top