34

I have a scenario where I wanted to change the name of a sheet in the spread-sheet.

  1. I tried creating a spread-sheet using ss = Workbook(). I think this is creating the spread-sheet with a sheet named "Sheet".

  2. I tried changing the name of the sheet using the below format:

    ss_sheet = ss.get_sheet_by_name('Sheet')
    ss_sheet.Name = 'Fruit'
    

But then the above step is not changing the sheet name as required. Is there anything wrong in the above step?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Vimo
  • 1,061
  • 3
  • 12
  • 22

1 Answers1

63

You can do this by changing the title attribute:

import openpyxl

ss = openpyxl.load_workbook("file.xlsx")
#printing the sheet names
ss_sheet = ss['Sheet']
ss_sheet.title = 'Fruit'
ss.save("file.xlsx")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Annapoornima Koppad
  • 1,376
  • 1
  • 17
  • 30
  • Also doesn't work if the another sheet in the same workbook also has that name, as you'd expect... – bigsee Jan 15 '19 at 09:02
  • 5
    Also note that get_sheet_by_name is [now deprecated](https://openpyxl.readthedocs.io/en/stable/api/openpyxl.workbook.workbook.html?highlight=get_sheet_by_name#openpyxl.workbook.workbook.Workbook.get_sheet_by_name). Replace `ss_sheet = ss.get_sheet_by_name('Sheet')` with `ss_sheet = ss['Sheet']` in the latest version. – bigsee Jan 15 '19 at 09:08
  • I know this is old but if you do this and there are any links inside other sheets to 'Sheet' they will be broken. – KevinDTimm Jan 18 '23 at 05:49