删除工作表后无法保存工作簿

编程入门 行业动态 更新时间:2024-10-10 10:24:45
本文介绍了删除工作表后无法保存工作簿-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)

更多推荐

删除工作表后无法保存工作簿

本文发布于:2023-06-02 01:32:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/431026.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!