How to write a list to xlsx using openpyxl

最后都变了- 提交于 2019-11-26 21:25:02

问题


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

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)

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

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

Cheers Thomas


回答1:


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




回答2:


from openpyxl import load_workbook,Workbook

wb=load_workbook('Book1.xlsx')
ws1=wb.get_sheet_by_name('Sheet1')

shs=wb.get_sheet_names()
print(type(shs))
# shs is list

for r in range(0,len(shs)):
    ws1.cell(row=r+1,column=1).value=shs[r]

wb.save('Book1.xlsx')



回答3:


Openpyxl does not allow you to write lists in excel cells, however if you convert the list into a string you can paste it into excel.

e.g. This would cause an error

my_list = ['1','2','3'] ws.cell(row=r, column=1).value = my_list

However this would paste the string of the list into excel

my_list = ['1','2','3'] new_list = str(my_list) ws.cell(row=r, column=1).value = new_list



来源:https://stackoverflow.com/questions/15004838/how-to-write-a-list-to-xlsx-using-openpyxl

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