Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading