Openpyxl 没有正确地从创建的工作簿中删除工作表
Openpyxl not removing sheets from created workbook correctly
所以我 运行 遇到了 remove_sheet()
与 openpxyl 的问题,我找不到答案。当我运行以下代码时:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.create_sheet("Sheet2")
wb.get_sheet_names()
['Sheet','Sheet2']
wb.remove_sheet('Sheet')
我收到以下错误:
ValueError: list.remove(x): x not in list
它不起作用,即使我尝试 wb.remove_sheet(0)
或 wb.remove_sheet(1)
,我也会得到同样的错误。有什么我想念的吗?
remove.sheet()
被赋予一个 sheet 对象,而不是 sheet!
的名称
因此对于您的代码,您可以尝试
wb.remove(wb.get_sheet_by_name(sheet))
同样,remove_sheet 也没有给出索引,因为它对实际的 sheet 对象进行操作。
这里有一个 示例(尽管它与您面临的问题不同,它恰好展示了如何正确调用 remove_sheet 方法)!
如果您使用 get_sheet_by_name
,您将得到以下内容:
DeprecationWarning
: Call to deprecated function get_sheet_by_name
(Use
wb[sheetname]
).
所以解决方案是:
xlsx = Workbook()
xlsx.create_sheet('other name')
xlsx.remove(xlsx['Sheet'])
xlsx.save('some.xlsx')
由于发布并回答了问题,Openpyxl 库发生了变化。
您不应使用 @cosinepenguin 指示的 wb.remove(wb.get_sheet_by_name(sheet))
,因为它现在已贬值(尝试使用它时会收到警告)但 wb.remove(wb[sheet])
在python3.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 是索引 sheet "sheet"
所以我 运行 遇到了 remove_sheet()
与 openpxyl 的问题,我找不到答案。当我运行以下代码时:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.create_sheet("Sheet2")
wb.get_sheet_names()
['Sheet','Sheet2']
wb.remove_sheet('Sheet')
我收到以下错误:
ValueError: list.remove(x): x not in list
它不起作用,即使我尝试 wb.remove_sheet(0)
或 wb.remove_sheet(1)
,我也会得到同样的错误。有什么我想念的吗?
remove.sheet()
被赋予一个 sheet 对象,而不是 sheet!
因此对于您的代码,您可以尝试
wb.remove(wb.get_sheet_by_name(sheet))
同样,remove_sheet 也没有给出索引,因为它对实际的 sheet 对象进行操作。
这里有一个
如果您使用 get_sheet_by_name
,您将得到以下内容:
DeprecationWarning
: Call to deprecated functionget_sheet_by_name
(Usewb[sheetname]
).
所以解决方案是:
xlsx = Workbook()
xlsx.create_sheet('other name')
xlsx.remove(xlsx['Sheet'])
xlsx.save('some.xlsx')
由于发布并回答了问题,Openpyxl 库发生了变化。
您不应使用 @cosinepenguin 指示的 wb.remove(wb.get_sheet_by_name(sheet))
,因为它现在已贬值(尝试使用它时会收到警告)但 wb.remove(wb[sheet])
在python3.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 是索引 sheet "sheet"