我会写一系列单元格,从列表中获取一系列值。
查看
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
我会使用循环执行此操作,并尝试以下操作:
start, stop = 20,26
for index, row in enumerate(ws.iter_rows()):
if start < index < stop:
ws.cell[index] = avg[index]
但它返回:
list index out of range
我怎么能这样做?我正在使用openpyxl 2.3
答案 0 :(得分:2)
您可以按如下方式指定行和列:
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')
这会迭代你的平均值,并使用Python的enumerate
函数同时为你计算。通过告诉它以值20开始,它可以用作写入单元格的行值。