How to iterate over worksheets in workbook, openpy

2019-04-06 16:20发布

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

2条回答
聊天终结者
2楼-- · 2019-04-06 16:40

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
查看更多
我只想做你的唯一
3楼-- · 2019-04-06 16:46

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)
查看更多
登录 后发表回答