简体   繁体   English

excel从列表中重命名多个工作表名称

[英]excel rename multiple sheet names from list

I have multiple sheets in excel converted from dataframe.我在 excel 中有多个从数据帧转换而来的工作表。 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.从数据框转换为 excel 后,我在列表中收集了工作表名称。

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'.但是,我得到了 AttributeError: 'list' object has no attribute 'title'。

Now, I want to rename the sheets to the dups value.现在,我想将工作表重命名为 dups 值。 I would like to know if it is possible.我想知道是否有可能。 Pleased to hear some suggestions.很高兴听到一些建议。

You can use openpyxl for this:您可以为此使用openpyxl

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可以for sheet in wb使用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.此功能可以帮助您实现您想要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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