openpyxl - populating a column using a list

别来无恙 提交于 2020-01-14 14:46:29

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/34128994/openpyxl-populating-a-column-using-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!