Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

python - How to write a list to Excel column?

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

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To assign a value to a cell, use =:

cell.value = statN

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?

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

You could also use Python's enumerate function:

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

(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).)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...