Reputation: 5097
I am using openpyxl to access all of the tabs in a spreadsheet using the following:
rawReturnwb = openpyxl.load_workbook(ValidationsDir)
for sheet in rawReturnwb.worksheets:
do something...
This works fine. I then would like to access the worksheet name to use else where in my code. However when I try access the worksheet name (printing sheet
to the console) I get:
<Worksheet "SheetName">
the type
of sheet is
<class 'openpyxl.worksheet.worksheet.Worksheet'>
Is there a way that I can just get the worksheet name returned (so my output would be "SheetName"
only. Or would I have to convert to string and strip the parts of the string I don't need?
Upvotes: 0
Views: 1079
Reputation: 12920
As suggested in comment of the question, sheet.title
is working.
For example, this is some code to get the Worksheet name from a given cell:
from openpyxl.cell import Cell
def get_cell_name(cell:Cell) -> str:
"""Get the name of the Worksheet of a given cell"""
return cell.parent.title
And in the case of the OP, the code could be something like:
rawReturnwb = openpyxl.load_workbook(ValidationsDir)
for sheet in rawReturnwb.worksheets:
# ...
if sheet.title == "Sheet1":
continue
# ...
FYI, the names of the variables are weird:
ValdiationsDir
is weird, for the path of an Excel FilerawReturnwb
could be renamed to book
for exampleUpvotes: 1