Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl how to switch default sheet

Tags:

xlsx

openpyxl

My xlsx file has 5 sheets, I can change fourth sheet content, after change, I save to a new file.

But when I open the new file, I need manual to select the fourth sheet.

How can I change the default sheet to fourth sheet?

Thanks!


update

It`s work! Thank you very much. But still a little question,

first and fourth sheet both select

I want this only fourth sheet select

like image 948
Kobe Nein Avatar asked Jan 07 '16 09:01

Kobe Nein


People also ask

How do I make a sheet active in openpyxl?

If wb = openpyxl. Workbook() calling wb. active give the title of the default first worksheet which is Sheet . Say I create another sheet ws1 = wb.

How do I move a sheet from one workbook to another in openpyxl?

Step1: Import the openpyxl library. Step2: Connect/load the Excel file to the program. Step3: Initialize variables with the source sheet name and destination sheet name. Step4: Create two variables to initialize with the total number of rows and columns in the source Excel sheet.


Video Answer


2 Answers

Simply set wb.active to the index of the sheet, eg. wb.active = 3 for the fourth sheet.

like image 104
Charlie Clark Avatar answered Jan 13 '23 18:01

Charlie Clark


I've had the same problem as Kobe with multiple sheets selected when manually opening the file after only setting wb.active and saving.

For me the workaround was explicitly setting the tabSelected property of every sheet in the workbook in addition to setting the active worksheet. Here is a minimal example:

import openpyxl

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

workbook.active = 2 # making the third sheet active

for sheet in workbook:
    if sheet.title == 'your_sheet_name':
        sheet.sheet_view.tabSelected = True
    else:
        sheet.sheet_view.tabSelected = False

workbook.save('your_file.xlsx')

With this only one sheet is selected after you manually open the file.

like image 23
Chillie Avatar answered Jan 13 '23 20:01

Chillie