So I ran into an issue with remove_sheet()
with openpxyl that I can't find an answer to. When I run the following code:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.create_sheet("Sheet2")
wb.get_sheet_names()
['Sheet','Sheet2']
wb.remove_sheet('Sheet')
I get the following error:
ValueError: list.remove(x): x not in list
It doesn't work, even if I try wb.remove_sheet(0)
or wb.remove_sheet(1)
, I get the same error. Is there something I am missing?
Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files.
The openpyxl. load_workbook() function returns a Workbook object.
If you use get_sheet_by_name
you will get the following:
DeprecationWarning
: Call to deprecated functionget_sheet_by_name
(Usewb[sheetname]
).
So the solution would be:
xlsx = Workbook()
xlsx.create_sheet('other name')
xlsx.remove(xlsx['Sheet'])
xlsx.save('some.xlsx')
remove.sheet()
is given a sheet object, not the name of the sheet!
So for your code you could try
wb.remove(wb.get_sheet_by_name(sheet))
In the same vein, remove_sheet is also not given an index, because it operates on the actual sheet object.
Here's a good source of examples (though it isn't the same problem you're facing, it just happens to show how to properly call the remove_sheet method)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With