openpyxl-使用列表填充列 [英] openpyxl - populating a column using a list

查看:426
本文介绍了openpyxl-使用列表填充列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在尝试在我的Python 3.5项目中使用openpyxl来生成一个excel文件,该文件的第一行(B1至M1)为Months,列(A2至列表长度)为我拥有的列表中的项目.现在,我可以使用以下方法使第一行正常工作:

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

但是,这不会从我的列表中拉出所有项目,而只会一遍又一遍地拉出第一个项目.由于某种原因,称为test的计数器未增加.我也尝试过使用ws1.iter_rows('A2:A15'),但这也只会从我的列表(firstNameList)中提取第一项.我对使用openpyxl非常陌生,希望对您有所帮助.

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.

谢谢!

推荐答案

问题在这里for col in range(1, 2):.您的范围只有一个元素:

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

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

因此,您仅循环一个元素.您可能希望range(1, 3)获得两列.

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

在Python中,range描述了一个区间,其中下限为包含值,上限为排除值.

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

这篇关于openpyxl-使用列表填充列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆