openpyxl - Active sheet is grouped to selected sheet

Viewed 1857


Using openpyxl, I loaded an existing workbook, and set a new active sheet. Then when opening the workbook in Excel i noticed that the new active sheet got grouped with the original one prior to changing with openpyxl.

Is there any way to ungroup the sheets or any explanation for this behavior?

wb = openpyxl.load_workbook("test.xlsx")
wb.active = 3
wb.save("test.xlsx")

And after running here are the "grouped" sheets i'm talking about: Grouped Sheets Image

It's as if the active sheet i set in the code ("Four") doesn't fully change the selected sheet but selects the new sheet alongside the originally selected sheet ("One")

Another discussion of the problem: https://bitbucket.org/openpyxl/openpyxl/issues/878/index-0-worksheet-creation-in-existing

Thanks!

2 Answers

Well i have solved the problem by changing a property called tabSelected to False.

You can access that property by getting the tab you want to deselect (in this case the tab named "One") as written in the code below.

wb = openpyxl.load_workbook("test.xlsx")
wb.active = 3
wb["One"].views.sheetView[0].tabSelected = False
wb.save("test.xlsx")

The third line turns the first tab to not selected therefore the only tab selected is the forth one. The solution is kinda more of a workaround for this weird problem but still it works anyway.

My solution was built off nir9's solution. I deselected all worksheets from being active and then made the worksheet I wanted to be active.

wb = openpyxl.load_workbook("test.xlsx")
template_copy = wb.copy_worksheet(template)
new_wk_sheet = wb['Template Copy']
new_wk_sheet.title = last_worksheet
for sheet in wb:
        wb[sheet.title].views.sheetView[0].tabSelected = False
wb.active = new_wk_sheet
wb.save("test.xlsx")
Related