Change sheet name using openpyxl in Python

In this tutorial, we will learn how to change sheet names using openpyxl in Python. We already know that each workbook can have multiple sheets. Let’s consider a workbook with more than one sheet and change their names.

Loading a workbook

We will load a workbook named ‘book.xlsx’ and print the names of the sheets in it.

import openpyxl
wb = openpyxl.load_workbook("book.xlsx")
print(wb.sheetnames)

Loading a workbook in openpyxl

Output:

['Firstsheet', 'Secondsheet']

The output shows the names of the sheets present in the workbook.

You can check: How to get sheet names using openpyxl in Python

Changing the sheet names in Openpyxl

  • To change the sheet name, we use the title property of the sheet.
ss_sheet1= wb['Firstsheet']
ss_sheet1.title ='First'
wb.save("book.xlsx")

Output:

Changing the sheet names in Openpyxl

Here, the name of the first sheet is changed from ‘Firstsheet‘ to ‘First‘.

  • We can also change any intermediate sheet name by using its name and title property.
ss_sheet2 = wb['Secondsheet']
ss_sheet2.title='Second'
wb.save("book.xlsx")

Output:

Change sheet name using openpyxl in Python

Hence, we changed the second sheet name from ‘Secondsheet‘ to ‘Second‘.

Leave a Reply

Your email address will not be published. Required fields are marked *