简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM