Xlwt Create Dynamic Number Of Worksheets Based On Input
Solution 1:
You're looking for the enumerate() method:
import xlwt as xlwt
wb = xlwt.Workbook()
names = ['a', 'b', 'c', 'd']
dataset = ['100', '200', '300', '400']
for name in names:
wb.add_sheet(name)
for n, datain enumerate(dataset):
ws = wb.get_sheet(n)
ws.write(1, 1, data)
# now do more things with ws if you like
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).
Solution 2:
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:
dataset= [[dataset1], [dataset2], etc...]
for innerset in dataset:for data in innerset:#create worksheet#add data#close worksheet
Solution 3:
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:
worksheet_names = ['a', 'b', 'c', 'd']
fornamein worksheet_names:
wb.add_sheet(name)
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:
dataset = ['100', '200', '300', '400']
ws = wb.get_sheet(2)
ws.write(1, 1, dataset[2])
ws.write(2, 1, "This is something else I want to write in the third worksheet")
ws = wb.get_sheet(0)
ws.write(1, 1, "Cell 1, 1 contains data from a dict")
ws.write(2, 1, "This is something else I want to write in the first worksheet")
ws = wb.get_sheet(1)
ws.write(1, 1, "The data in this cell comes from a different dict")
ws.write(2, 1, "Write this in the second worksheet")
ws = wb.get_sheet(3)
ws.write(1, 1, "This is the 4th worksheet")
Post a Comment for "Xlwt Create Dynamic Number Of Worksheets Based On Input"