简体   繁体   English

如何使用openpyxl将列表写入xlsx

[英]How to write a list to xlsx using openpyxl

I have a list of some values in Python and want to write them into an Excel-Spreadsheet using openpyxl. 我在Python中有一些值的列表,并希望使用openpyxl将它们写入Excel-Spreadsheet。

So far I tried, where lstStat is a list of integers that needs to be written to the Excel file: 到目前为止,我尝试过,其中lstStat是需要写入Excel文件的整数列表:

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. 我得到一个TypeError:'NoneType'对象不能用于代码snipet中的最后一行。

Can you help me out how to write my data to the Excel file? 你能帮我解决如何将我的数据写入Excel文件的问题吗?

Cheers Thomas 干杯托马斯

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 . 请注意,现在,对于lstStat 每个元素,您正在编写整个范围 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. 你想要做的只是循环遍历lstStatlstStat增加行号。 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: 您还可以使用Python的enumerate函数:

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) .) (注意,从OpenPyXL版本2.0.0开始 ,A1被引用为cell(row=1, column=1) ;在早期版本中,A1是cell(row=0, column=0) 。)

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

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. Openpyxl不允许您在Excel单元格中编写列表,但是如果将列表转换为字符串,则可以将其粘贴到Excel中。

eg 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 但是,这会将列表的字符串粘贴到excel中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM