Search code examples
pythonexcelopenpyxl

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?


Solution

  • 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]