0

I have seen many examples on how to access the active sheet in an excel workbook, and how to specify which sheet to activate based on the name of the sheet, but is there a way to loop through all of the sheets without specifying the name of the sheets and perform a task on each on, even when I do not input the actual names of the sheet myself?

def main(workbook_name):
    wb = openpyxl.load_workbook(workbook_name)
    sheetNameList = wb.get_sheet_names()
    for sheetName in sheetNameList:    
          [activate the sheet sheetName]
          [perform function on sheetName]
    wb.save(workbook_name)

so far my code only performs the function on the active worksheet because I cannot figure out how to activate the others.

I imagine there is a simple solution to this and I am just not finding the right function.

Thanks for your help.

Mwspencer
  • 1,142
  • 3
  • 18
  • 35

1 Answers1

1

Sure:

for sheetName in sheetNameList:
    ws_active = wb.get_sheet_by_name(sheetName)
    ws_active.append([1, 2, 3])

Or something along those lines.

Ari Cooper-Davis
  • 3,374
  • 3
  • 26
  • 43
  • Perfect thanks, this is much more clear than similar questions, what is the purpose of ws_active.append([1,2,3]), it did not seem necessary when I ran the loop without it. – Mwspencer Mar 21 '17 at 20:52
  • My pleasure, good luck with the project. That line is just demonstrating how to refer to the active sheet. – Ari Cooper-Davis Mar 22 '17 at 10:38