Openpyxl not removing sheets from created workbook correctly

Viewed 17856

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?

4 Answers

If you use get_sheet_by_name you will get the following:

DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[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)!

Since the question was posted and answered, the Openpyxl library changed.

You should not use wb.remove(wb.get_sheet_by_name(sheet)) as indicated by @cosinepenguin since it is now depreciated ( you will get warnings when trying to use it ) but wb.remove(wb[sheet])

In python 3.7

 import openpyxl

 wb = openpyxl.Workbook()

 ws = wb.create_sheet("Sheet2")

 n=wb.sheetnames

 #sheetname =>get_sheet_names()

 wb.remove(wb["Sheet"])

 '#or can use' 

 wb.remove(wb[n[1]])

1 is index sheet "sheet"

you can visit this link for more info

Related