ali
ali

Reputation: 151

excel rename multiple sheet names from list

I have multiple sheets in excel converted from dataframe. I have collected the sheetnames in a list. I want to change the sheetname to the duplicate column values in which I have collected as shown below. Here is my code:

dups = df.set_index('Group').index.get_duplicates() 

After converting from dataframe to excel I have collected the sheetnames in a list.

xls = pd.ExcelFile('filename', on_demand=True)
sheets=xls.sheet_names

I also used as shown below:

for i in group: #names to be renamed, collected as list 
    wb=openpyxl.load_workbook('file.xlsx')
    worksheet = wb.get_sheet_names()
    worksheet.title = i
wb1.save('file.xlsx')

But, I got the AttributeError: 'list' object has no attribute 'title'.

Now, I want to rename the sheets to the dups value. I would like to know if it is possible. Pleased to hear some suggestions.

Upvotes: 0

Views: 3084

Answers (2)

Vahan Margaryan
Vahan Margaryan

Reputation: 1

It is possible to iterate over the workbook using for sheet in wb

Here is an example:

import openpyxl
import os
    
os.chdir('C:\\Users\\Vahan\\Desktop\\xlsx')
wb = openpyxl.load_workbook('example.xlsx')

for sheet in wb: # or wb.worksheets
    sheet.title = 'RenamedSheets'
    
wb.save('example.xlsx')

This functionality may help you achieve what you are trying to do.

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34056

You can use openpyxl for this:

import openpyxl

file_loc = 'myexcel.xlsx'

workbook = openpyxl.load_workbook(file_loc)
worksheet = workbook.get_sheet_by_name('Sheet1')
worksheet.title = 'MySheetName'
workbook.save(file_loc)

You can run this in a loop to rename all the sheets. Let me know if this helps.

Upvotes: 1

Related Questions