rivu
rivu

Reputation: 2534

getting sheet names from openpyxl

I have a moderately large xlsx file (around 14 MB) and OpenOffice hangs trying to open it. I was trying to use openpyxl to read the content, following this tutorial. The code snippet is as follows:

 from openpyxl import load_workbook
 wb = load_workbook(filename = 'large_file.xlsx', use_iterators = True)
 ws = wb.get_sheet_by_name(name = 'big_data') 

The problem is, I don't know the sheet name, and Sheet1/Sheet2.. etc. didn't work (returned NoneType object). I could not find a documentation telling me How to get the sheet names for an xlsx files using openpyxl. Can anyone help me?

Upvotes: 87

Views: 200619

Answers (6)

Vijay Bokade
Vijay Bokade

Reputation: 179

To get the names of the sheets from workbook;

List_of_sheets = wb.sheetnames
print(List_of_sheets) 

Upvotes: 1

lulu
lulu

Reputation: 1

for worksheet in workbook:
    print(worksheet.name)

Upvotes: 0

lalebarde
lalebarde

Reputation: 1816

As a complement to the other answers, for a particular worksheet, you can also use cf documentation in the constructor parameters:

ws.title

Upvotes: 14

ismail
ismail

Reputation: 175

python 3.x for get sheet name you must use attribute

g_sheet=wb.sheetnames

return by list

for i in g_sheet:
    print(i)

**shoose any name **

ws=wb[g_sheet[0]]

or ws=wb[any name] suppose name sheet is paster

ws=wb["paster"]

Upvotes: 5

Kamaraj
Kamaraj

Reputation: 83

As mentioned the earlier answer you can get the list of sheet names by using the ws.sheetnames

But if you know the sheet names you can get that worksheet object by

ws.get_sheet_by_name("YOUR_SHEET_NAME")

Another way of doing this is as mentioned in earlier answer

ws['YOUR_SHEET_NAME']

Upvotes: 3

alecxe
alecxe

Reputation: 474191

Use the sheetnames property:

sheetnames

Returns the list of the names of worksheets in this workbook.

Names are returned in the worksheets order.

Type: list of strings

print (wb.sheetnames)

You can also get worksheet objects from wb.worksheets:

ws = wb.worksheets[0]

Upvotes: 155

Related Questions