0

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.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 1. Don't call your variables `list` because it shadows the builtin type. 2. Please provide a [mre] that we can run _as-is_ and that will reproduce your issue. We don't know what your `list` contains. It seems like your code should work fine, and indeed it does (as demonstrated by [jmcnamara](https://stackoverflow.com/a/72061022/843953)) – Pranav Hosangadi Apr 29 '22 at 17:23

1 Answers1

0

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

jmcnamara
  • 38,196
  • 6
  • 90
  • 108
  • "Your code works fine" is not an answer. You should vote to close as not reproducible – Pranav Hosangadi Apr 29 '22 at 17:27
  • @Pravan Hosangadi I disagree. It is an answer insofar as it allows the OP to consider that code they though wasn't working does, or can, work in another context. That allows them to figure out where the actual issues is (for example the attributes of the object may not be initialised). – jmcnamara Apr 29 '22 at 17:52
  • It was adding data into multiple sheets but not resetting the row number for new sheets. Reset the row number and its working fins as required. – Govind Rajpurohit May 02 '22 at 05:20