How to write a list to Excel column?
Solution 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)
.)
Solution 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')