Jezza
Jezza

Reputation: 1

I can't get the sheetnames function to work in openpyxl

Hope I'm not duplicating threads here. Had a good look and can't find anyone else having the same issue.

I'm using the latest version of openpyxl (downloaded and installed using pip today!)

All I am trying to do is call the sheetnames in a particular excel file and, no matter what I try, the sheetnames function will not work.

The error I get is:

Traceback (most recent call last):
File "C:/Users/JeremyAinley/AppData/Local/Programs/Python/Python37-32/xlsx reader/get sheetnames.py", line 9, in <module>
sheetnames = wb.sheetnames
AttributeError: 'Worksheet' object has no attribute 'sheetnames'

Here is my code:

import openpyxl
import os
from openpyxl import Workbook
from openpyxl import load_workbook


wb = load_workbook(r'C:\Users\Jeremy\Desktop\FilesZ\PDT.xlsx')
sheetnames = wb.sheetnames
print(sheetnames)
ws = wb.active

Any help would be greatly appreciated!

Thanks!

Upvotes: 0

Views: 1491

Answers (2)

Lemon Lee
Lemon Lee

Reputation: 1

If you created the python program filename same with 'openpyxl.py', you will got clashing, please can make another program filename instead of 'openpyxl.py'.

Upvotes: 0

Woody1193
Woody1193

Reputation: 8010

As was suggested in the comments, your problem here is that you're assigning wb.active to wb, which would mean that wb was no longer a workbook but rather the active sheet on said workbook. To fix this, we just have to rename our variables:

import openpyxl
import os
from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook(r'C:\Users\Jeremy\Desktop\FilesZ\PDT.xlsx')
active_workbook = wb.active
names = wb.sheetnames
print(names)

Upvotes: 1

Related Questions