Skip to content
Advertisement

Python xlsxwriter loop through each worksheet in a workbook

I want to iterate through each worksheet that I have created in a workbook with add_worksheet function. I want to do this with all the available sheets in the workbook and write ‘Hello’ in cell ‘A1’ of each sheet.

Here is the code I am trying:

workbook = xlsxwriter.Workbook('test.xlsx',{'nan_inf_to_errors': True})
WS1 = workbook.add_worksheet('Sheet A')
WS2 = workbook.add_worksheet('Sheet B')
WS2 = workbook.add_worksheet('Sheet C')

for WS in enumerate(workbook.worksheets):
    WS.write('A1','Hello!')

workbook.close()

I was expecting it to write ‘Hello’ in cell ‘A1’ for each available sheet in the workbook.

Getting this error : TypeError: ‘method’ object is not iterable

Advertisement

Answer

You need to remove enumerate and add parenthesis to workbook.worksheets.

Try this :

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx', {'nan_inf_to_errors': True})

WS1 = workbook.add_worksheet('Sheet A')
WS2 = workbook.add_worksheet('Sheet B')
WS2 = workbook.add_worksheet('Sheet C')

for WS in workbook.worksheets():
    WS.write('A1','Hello!')

workbook.close()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement