0

I have a folder with multiple Excel workbooks. In each workbook there are multiple sheets. For some of these sheets, I want to harmonize the name.

For example:

  • workbook #1 has 2 sheets : A, B
  • workbook #2 has 3 sheets : A1, B, C
  • workbook #3 has 2 sheets : A Test, B, C

I want to standardize the name of the A sheets so A, A1 and A Test will have the same name (A Standard for example).

How can I do this with Python?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Arthur NS
  • 19
  • 2
  • In a [similar question](https://stackoverflow.com/questions/39540789/how-to-rename-the-sheet-name-in-the-spread-sheet-using-python) the answer does it using `openpyxl`. – Jeronimo Aug 19 '21 at 11:24
  • @Jeronimo If you think this question has an answer somewhere else in this site - [flag it as duplicate](https://stackoverflow.com/help/privileges/flag-posts) instead of posting a link as a comment... – Tomerikoo Aug 19 '21 at 11:49
  • @Arthur Please specify what have you tried? What libraries reading Excel are at your disposal? What is ***really*** your problem here? Opening the files? Finding the relevant sheets? Renaming the sheets? What research have you done about this problem? There are a few existing SO questions about this issue. Did you see them? Did you not help you in any way? Please take the [tour] and read about [ask] – Tomerikoo Aug 19 '21 at 11:51

1 Answers1

1

I don't exactly know how to fix your problem, but I can point you in the right direction. In the little script below I am using openpyxl (a Python library to read/write Excel 2010 xlsx/xlsm files) to select all sheets starting with the letter 'A' and assigns them a new name.

import openpyxl

# open a new workbook
workbook_1 = openpyxl.load_workbook('file.xlsx')

# print all the existing sheetnames from workbook_1
all_sheets = workbook_1.worksheets
print(all_sheets)

# select the checker you want to use
check = 'A'

# store the selected sheets (based on the check variable) in a list
selected_sheets = [sheet for sheet in all_sheets if sheet.title[0].lower() == check.lower()]

# print the selected sheet list
print(selected_sheets)

# loop over the selected sheets
for sheet in selected_sheets:
    # change the sheet title
    sheet.title = 'New name'

# save the worksheet
workbook_1.save('file.xlsx')

You can find openpyxl documentation here. I think with a little effort you can solve this problem by looking at my sample script and by reading through the documentation.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Desmanado
  • 152
  • 9