如何使用openpyxl将列表写入xlsx [英] How to write a list to xlsx using openpyxl

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

问题描述

我有一些Python值的列表,并希望使用openpyxl将它们写入Excel电子表格.

I have a list of some values in Python and want to write them into an Excel-Spreadsheet using openpyxl.

到目前为止,我已经尝试过,其中lstStat是需要写入Excel文件的整数列表:

So far I tried, where lstStat is a list of integers that needs to be written to the Excel file:

for statN in lstStat:
    for line in ws.range('A3:A14'):
        for cell in line:
            cell.value(statN)

我收到TypeError:代码段的最后一行无法调用'NoneType'对象.

I'm getting a TypeError: 'NoneType' object is not callable for the last line in the code snipet.

您能帮我怎样将数据写入Excel文件吗?

Can you help me out how to write my data to the Excel file?

欢呼托马斯

推荐答案

要将值分配给单元格,请使用=:

To assign a value to a cell, use =:

cell.value = statN

您还需要修复循环.请注意,现在,对于lstStat中的每个元素,您正在编写整个范围.除了达不到您的期望之外,它的灵活性也更低:如果lstStat具有更多或更少的元素,会发生什么?

You also need to fix your loops. Notice that right now, for each element in lstStat, you are writing the entire range. Besides not being what you intended, it also is less flexible: What happens if lstStat has more or fewer elements?

您想要做的就是循环遍历lstStat并随行增加行号.像

What you want to do is just loop over lstStat and increment the row number as you go. Something like

r = 3
for statN in lstStat:
    ws.cell(row=r, column=1).value = statN
    r += 1

您还可以使用Python的enumerate函数:

You could also use Python's enumerate function:

for i, statN in enumerate(lstStat):
    ws.cell(row=i+3, column=1).value = statN

(请注意,从 OpenPyXL 2.0版开始,A1被引用为cell(row=1, column=1) .0 ;在早期版本中,A1是cell(row=0, column=0).)

(Note that A1 is referenced as cell(row=1, column=1) as of OpenPyXL version 2.0.0; in earlier versions, A1 was cell(row=0, column=0).)

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

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