簡體   English   中英

OpenPyXL:在單元格范圍內迭代

[英]Openpyxl: iterate on range of cell

我將從列表中獲取一系列值寫入單元格區域。

視圖

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

您可以如下指定行和列:

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開頭,則可以將其用作寫入單元格的行值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM