JRS
JRS

Reputation: 3

openpyxl, deactivate tab, so when user opens in Excel, only one tab is active

I am creating a new worksheet by copying the worksheet that was active when the workbook was used last and am using workbook.copy_worksheet to do it.

Once the worksheet is created, I use workbook.active to switch to the new worksheet, and make it the active worksheet. Unfortunately, the previous worksheet that was active, does not get deactivated, so now both worksheets are active at the same time.

I have attempted other methods that are shown on this page, Set the active sheet with openpyxl, so please do not point me there, those are not my issue.

When I open the workbook manually, the last active worksheet and the worksheet I created are both active, like when you hold the control key to select multiple sheets within Excel.

How do I deactivate the other worksheet using openpyxl, so when a user opens the workbook in Excel, only one worksheet is active?

Some test code:

def create_new_tab_in_workbook():
    """Create a new tab in TestWorkbook.xlsx"""
    from openpyxl import load_workbook

    workbookString = r'C:\TemporaryRemoveToday\WORKING\TestWorkbook.xlsx'
    workbook = load_workbook(filename=workbookString)
    newWorksheet = workbook.copy_worksheet(workbook.active)
    newWorksheetTitle = workbook.active.title[5:] + '-' + str(int(workbook.active.title[5:]) + 54)
    newWorksheet.title = newWorksheetTitle
    workbook.active = newWorksheet
    print(newWorksheet.title)
    workbook.save(filename=workbookString)

create_new_tab_in_workbook()

Upvotes: 0

Views: 173

Answers (1)

moken
moken

Reputation: 6639

Disable 'tabSelected' on the Sheet view

def create_new_tab_in_workbook():
    """Create a new tab in TestWorkbook.xlsx"""
    from openpyxl import load_workbook

    # workbookString = r'C:\TemporaryRemoveToday\WORKING\TestWorkbook.xlsx'
    workbook = load_workbook(filename=workbookString)
    newWorksheet = workbook.copy_worksheet(workbook.active)
    newWorksheetTitle = workbook.active.title[5:] + '-' + str(int(workbook.active.title[5:]) + 54)
    newWorksheet.title = newWorksheetTitle
    
    ### Disable the current active Sheet 
    workbook[workbook.active.title].views.sheetView[0].tabSelected = False

    workbook.active = newWorksheet
    print(newWorksheet.title)
    workbook.save(filename=workbookString)

create_new_tab_in_workbook()

Upvotes: 1

Related Questions