AlexTheGreat26
AlexTheGreat26

Reputation: 33

openpyxl - populating a column using a list

So I have been trying to use openpyxl with my Python 3.5 project to produce an excel file that has the top row(B1 to M1) being Months and the column(A2 to length of list) being items from a list I have. Now I can get the top row working fine using this:

for row in ws1.iter_rows('B1:M1'):
    counter=0
    for cell in row:
      cell.value = months[counter]
      counter=counter+1

However I cannot use the same method to populate the column. I have tried:

for row in range(2, 1 + len(firstNameList)):
    test=0
    for col in range(1, 2):
        test2 = firstNameList[test]
        ws1.cell(column=col, row=row, value=test2)
        test = test + 1

This however does not pull all item from my list but only pulls the first item over and over again. The counter called test is not being incremented for some reason. I also tried using ws1.iter_rows('A2:A15') but this also only pulls the first item from my list(firstNameList). I am very new to using openpyxl and would appreciate any help.

Thanks!

Upvotes: 3

Views: 2325

Answers (1)

Mike Müller
Mike Müller

Reputation: 85462

The problem is here for col in range(1, 2):. Your range has only one element:

>>> list(range(1, 2))
[1]

Therefore, you loop over only one element. You likely want range(1, 3) to get two columns.

In Python range describes an interval where the lower bound is inclusive and the upper bound is exclusive.

Upvotes: 3

Related Questions