'Write to multiple worksheets

I need to write to multiple sheets with sheets name stored in a list. Below is my code

for row_num, obj in enumerate(list,1):
    sheet = workbook.add_worksheet(obj.Attribute1)
    sheet.write(row_num, 0, obj.Attr1)
    sheet.write(row_num, 1, obj.Attr2)
    sheet.write(row_num, 2, obj.Attr3)
    ....

For each object in list i want to create a sheet. Above code is creating multiple sheets with desired name but data is only present in the first sheet.



Solution 1:[1]

It should work as expected.

Here is your sample code wrapped into a working example:

import xlsxwriter


class MyObj:
   def __init__(self, id):
      self.Attribute1 = 'Sheet%s' % id
      self.Attr1 = 'Attr1'
      self.Attr2 = 'Attr2'
      self.Attr3 = 'Attr3'

obj_list = []
for id in range(1, 4):
    my_obj = MyObj(id)
    obj_list.append(my_obj)

workbook = xlsxwriter.Workbook('test.xlsx')

for row_num, obj in enumerate(obj_list, 1):
    sheet = workbook.add_worksheet(obj.Attribute1)
    sheet.write(row_num, 0, obj.Attr1)
    sheet.write(row_num, 1, obj.Attr2)
    sheet.write(row_num, 2, obj.Attr3)

workbook.close()

Output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1