删除工作表后无法保存工作簿-openpyxl [英] Can't save a workbook after deleting sheets - openpyxl

查看:180
本文介绍了删除工作表后无法保存工作簿-openpyxl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一张纸,主要删除除我需要的纸之外的所有纸.我将遍历所有工作表,并删除对我的任务无用的工作表.

I'm manipulating a sheet, mainly deleting all the sheets but the one that I need. I will loop through all the sheets, and delete the sheets that is not useful for my task.

删除后,我尝试保存,但是会引发错误.

After deleting, I tried to save but it throws an error.

File "C:\Users\myUser\Anaconda3\lib\site-packages\openpyxl\workbook\workbook.py", line 130, in active
return self._sheets[self._active_sheet_index]

这是我的剧本

wb = load_workbook("File.xlsx")

ws1 = wb["Employee Info"]
ws1.freeze_panes = None

ws_active = wb.get_sheet_by_name("Employee Info")

### delete other sheets but Employee Info
for sheet in wb.worksheets:
    if sheet.title != 'Employee Info':
        print("removing " + sheet.title)
        wb.remove_sheet(sheet)

print("remaining sheets:")
for sheet in wb.worksheets:
    print("    " + sheet.title)

### TODO
### loop through the files in a directory

### TODO
### see if readable by ETL 

print("saving the wb")

wb.save("modified.xlsx")

删除后,我检查了工作簿.它具有我想要的工作表.只是不确定为什么它没有检测到剩余的1张纸.

after deleting, I checked the workbook. And it has the sheet that I am looking for. Just not sure though why it is not detecting the remaining 1 sheet.

要添加更多详细信息,excel文件有8张纸,我需要的纸页位于第5张纸上.

To add more details, the excel file has 8 sheets, the sheet that I am after is on the 5th sheet.

推荐答案

对我来说,它正在使用2.4.2版本:

For me this is working with 2.4.2 version:

import openpyxl

workbook = openpyxl.load_workbook('test.xlsx')

for i in workbook.worksheets:
    if i.title != 'Employee Info':
        workbook.remove_sheet(i)

workbook.save('test2.xlsx')

尝试简单看看它是否有效. 您还可以使用workbook.sheetnames查看工作表名称:

Try it simple to see if its working. You can also use the workbook.sheetnames to see the sheetnames:

for sheet in workbook.sheetnames:
    print(sheet)

这篇关于删除工作表后无法保存工作簿-openpyxl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆