How to iterate over worksheets in workbook, openpyxl

Mike picture Mike · Aug 28, 2013 · Viewed 31.9k times · Source

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

Answer

alecxe picture alecxe · Aug 28, 2013

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