I know how to create multiple worksheets and write to them if I know in advance how many worksheets I will need. For example, this code works fine if I only have 3 worksheets. (I can use a for loop to dictate the contents of each worksheet):
import xlwt as xlwt
workbook = xlwt.Workbook()
style = xlwt.XFStyle()
ws1 = workbook.add_sheet("Worksheet 1")
ws2 = workbook.add_sheet('Worksheet 2')
ws3 = workbook.add_sheet('Worksheet 3')
# For loop to dictate contents of each worksheet here...
worksheet = ws1
worksheet.write(1, 1, 'Welcome to Worksheet 1', style)
worksheet = ws2
worksheet.write(1, 1, 'Welcome to Worksheet 2', style)
workbook.save(r'C:\Users\...\Desktop\...\mult_worksheets.xls')
However, what I want to do is gather data and create new worksheets that I can write to based on the number of datasets gathered. I won't know ahead of time how many worksheets I will need to create and write to. It may be 1 dataset or up to 10.
I know that worksheet objects are created when you call workbook.add_sheet('Name'). For example:
ws1 = workbook.add_sheet('Worksheet 1')
I need the worksheet instance "ws1" in order to write to that worksheet. How can I create only the number of worksheet instances that I need and be able to write to them?
If I gather a set of 4 datasets, I need to create 4 worksheets, with the names of the worksheets and the contents determined by the datasets.
To clarify, lets say I create a list of dataset names like this:
worksheet_names = ['CA Stats', "TX Stats", "NY Stats", "FL Stats"]
These will be used as the names of the worksheets.
And each worksheet will have its own data. For example:
worksheet_data = ['Welcome to CA Stats', "Welcome to TX Stats", "Welcome to NY Stats", "Welcome to FL Stats"]
Any help is appreciated!
You're looking for the enumerate() method:
The main thing is that the names and dataset are pairwise-ordered the same way (so 'b' is the name of the sheet which will have the data '200' in it).
How are you getting your dataset(s)? Why are you unable to determine how many sheets you need at the point the dataset(s) are retrieved?
Update:
An example:
Thanks to melipone, I now have the answer to my question. However, to clarify for anyone else who sees this, I want to point out that enumerate() is not germane to the question and is not necessary. Once the worksheets have been created like this:
It is possible to write to any of the worksheets in any order you want, with any data you want. All you need to know is the index position of the worksheet and it can be accessed with "ws = wb.get_sheet(index_position)". For example: