Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over worksheets in workbook, openpyxl

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
like image 314
Mike Avatar asked Aug 28 '13 18:08

Mike


People also ask

Is openpyxl faster than pandas?

Step 3: Load with Openpyxl Still slow but a tiny drop faster than Pandas. Openpyxl Documentation: Memory use is fairly high in comparison with other libraries and applications and is approximately 50 times the original file size.


2 Answers

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
like image 97
alecxe Avatar answered Oct 05 '22 10:10

alecxe


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

for sheet in wb:
    ws = wb[sheet]
    print('Now in sheet: ' + ws.title)
like image 21
Tony S Avatar answered Oct 05 '22 10:10

Tony S