[英]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.所以我在使用remove_sheet()
遇到了remove_sheet()
的问题,我找不到答案。 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.它不起作用,即使我尝试wb.remove_sheet(0)
或wb.remove_sheet(1)
,我wb.remove_sheet(1)
得到同样的错误。 Is there something I am missing?有什么我想念的吗?
If you use get_sheet_by_name
you will get the following:如果您使用get_sheet_by_name
您将获得以下信息:
DeprecationWarning
: Call to deprecated functionget_sheet_by_name
(Usewb[sheetname]
).DeprecationWarning
:调用不推荐使用的函数get_sheet_by_name
(使用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! remove.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.同样,remove_sheet 也没有给出索引,因为它对实际的工作表对象进行操作。
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)!这是一个很好的示例来源(尽管这与您面临的问题不同,但它恰好展示了如何正确调用 remove_sheet 方法)!
Since the question was posted and answered, the Openpyxl library changed.由于问题已发布并得到解答,Openpyxl 库发生了变化。
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])
你不应该使用wb.remove(wb.get_sheet_by_name(sheet))
所指示@cosinepenguin ,因为它现在贬值(尝试使用它时,你会得到警告),但wb.remove(wb[sheet])
In python 3.7在蟒蛇 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" 1 是索引表“表”
you can visit this link for more info您可以访问此链接以获取更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.