Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openpyxl not removing sheets from created workbook correctly

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?

like image 974
EliSquared Avatar asked Sep 20 '17 16:09

EliSquared


People also ask

Does openpyxl work with Xlsx?

Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files.

What does the openpyxl Load_workbook () function return?

The openpyxl. load_workbook() function returns a Workbook object.


2 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')
like image 152
4 revs Avatar answered Sep 22 '22 17:09

4 revs


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)!

like image 28
cosinepenguin Avatar answered Sep 20 '22 17:09

cosinepenguin