remove_sheet会导致IndexError:在保存表上列出超出范围的索引

时间:2023-01-15 16:41:35

I am trying to use openpyxl to:

我正在尝试使用openpyxl:

  1. Open an Excel (2016) workbook which contains 3 worksheets (Sheet1,Sheet2,Sheet3)
  2. 打开包含3个工作表的Excel(2016)工作簿(Sheet1,Sheet2,Sheet3)
  3. Remove a worksheet (Sheet2)
  4. 删除工作表(Sheet2)
  5. Save the workbook to a different workbook minus Sheet2

    将工作簿保存到另一个工作簿- Sheet2

    from openpyxl import load_workbook
    wb = load_workbook("c:/Users/me/book1.xlsx")
    ws = wb.get_sheet_by_name('Sheet2')
    wb.remove_sheet(ws)
    wb.save("c:/Users/me/book2.xlsx")

The wb.save will generate an IndexError: list index out of range error and produce a corrupted book2.xlsx file which Excel cannot open.

白平衡。save将生成一个IndexError:超出范围的列表索引错误并生成一个已损坏的book2。无法打开的xlsx文件。

1 个解决方案

#1


1  

I run into similar problem, only with xlwt library. Regardless, the cause is the same, You remove the sheet which is set as active sheet. So, to fix this, before saving workbook, set some other sheet as active. In openpyxl, it would be something like this:

我遇到了类似的问题,只有在xlwt库中。无论如何,原因是相同的,您删除了被设置为活动表单的表单。因此,要修复这个问题,在保存工作簿之前,将其他一些工作表设置为活动的。在openpyxl中,它是这样的:

from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb._active_sheet_index = 0
wb.save("c:/Users/me/book2.xlsx")

I must mention that this is not very good programming practice, but there is no method to set active sheet, only to get one.

我必须指出,这不是很好的编程实践,但是没有方法来设置活动的表单,只有得到一个。

EDIT: Just found out that this repo was moved to bitbucket, and found that it has method for setting active sheet. Just use:

编辑:刚刚发现这个repo被移动到bitbucket,并发现它有设置活动表单的方法。只使用:

wb.active = 0

#1


1  

I run into similar problem, only with xlwt library. Regardless, the cause is the same, You remove the sheet which is set as active sheet. So, to fix this, before saving workbook, set some other sheet as active. In openpyxl, it would be something like this:

我遇到了类似的问题,只有在xlwt库中。无论如何,原因是相同的,您删除了被设置为活动表单的表单。因此,要修复这个问题,在保存工作簿之前,将其他一些工作表设置为活动的。在openpyxl中,它是这样的:

from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb._active_sheet_index = 0
wb.save("c:/Users/me/book2.xlsx")

I must mention that this is not very good programming practice, but there is no method to set active sheet, only to get one.

我必须指出,这不是很好的编程实践,但是没有方法来设置活动的表单,只有得到一个。

EDIT: Just found out that this repo was moved to bitbucket, and found that it has method for setting active sheet. Just use:

编辑:刚刚发现这个repo被移动到bitbucket,并发现它有设置活动表单的方法。只使用:

wb.active = 0