Reputation: 57
I would write to a range of cells a sequence of values taken from a list.
VIEW
def create_excel(avg):
wb = load_workbook('output/file_base.xlsx')
ws = wb.active
ws['D20'] = avg[0]
ws['D21'] = avg[1]
ws['D22'] = avg[2]
ws['D23'] = avg[3]
ws['D24'] = avg[4]
ws['D25'] = avg[5]
wb.save('out.xlsx')
return 1
I would do this using a loop, and I have tried the following:
start, stop = 20,26
for index, row in enumerate(ws.iter_rows()):
if start < index < stop:
ws.cell[index] = avg[index]
but it returns:
list index out of range
How can I can do this? I am using openpyxl 2.3
Upvotes: 1
Views: 5417
Reputation: 46759
You can specify row and columns as follows:
import openpyxl
avg = [10, 20, 25, 5, 32, 7]
wb = openpyxl.load_workbook('output/file_base.xlsx')
ws = wb.active
for row, entry in enumerate(avg, start=20):
ws.cell(row=row, column=4, value=entry)
wb.save('out.xlsx')
This iterates over your averages, and uses Python's enumerate
function to count for you at the same time. By telling it to start with a value of 20, it can then be used as the row value for writing to a cell.
Upvotes: 3