简体   繁体   English

OpenPyxl,使用 .format() 跨列循环公式?

[英]OpenPyxl, loop a formula across columns using .format()?

I use openpyxl to create Excel files from Python.我使用 openpyxl 从 Python 创建 Excel 文件。 I want to take a pandas Dataframe, insert it into a spreadsheet and then summarize column A, B and C with a for loop.我想获取一个 Pandas Dataframe,将其插入到电子表格中,然后使用 for 循环总结 A、B 和 C 列。 (formula in cell A5, B5 and C6 ). (单元格 A5、B5 和 C6 中的公式)。 However, I'm struggle with how to change the formula string in the loop so I summarize the correct column.但是,我很难在循环中更改公式字符串,因此我总结了正确的列。

data = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                   columns=['a', 'b', 'c'])

data

wb1 = openpyxl.Workbook()
ws1 = wb1.active

rows = dataframe_to_rows(data, index=False, header=False)
for r_idx, row in enumerate(rows, 2):
    for c_idx, value in enumerate(row, 1):
        ws1.cell(row=r_idx, column=c_idx, value=value)

for col in ws1.iter_cols(min_row=5, max_row=5, min_col=1, max_col=3):
    for cell in col:
        cell.value = '=SUMMA(A2:A4)' # can I use .format() here in a smart way so A2:A4 changes to # B2:B4 and so on?         
        
wb1.save('test.xlsx')

This should work:这应该有效:

for col in ws1.iter_cols(min_row=5, max_row=5, min_col=1, max_col=3):
    for cell in col:
        cell.value = '=SUMMA({0}2:{0}4)'.format(cell.column)

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

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