简体   繁体   English

使用Python将公式写入Excel

[英]Write formula to Excel with Python

I am in the process of brain storming how to best tackle the below problem. 我正在脑力激荡的过程中如何最好地解决以下问题。 Any input is greatly appreciated. 任何输入都非常感谢。

Sample Excel sheet columns: Excel工作表列示例:

Column A  |  Column B  | Column C
Apple     |  Apple     |
Orange    |  Orange    |
Pear      |  Banana    |

I want Excel to tell me whether items in column A and B match or mismatch and display results in column C. The formula I enter in column C would be =IF(A1=B1, "Match", "Mismatch") 我希望Excel告诉我A列和B列中的项目是否匹配或不匹配,并在C列中显示结果。我在C列中输入的公式将是=IF(A1=B1, "Match", "Mismatch")

On excel, I would just drag the formula to the rest of the cells in column C to apply the formula to them and the result would be: 在excel上,我只是将公式拖到C列的其余单元格中,将公式应用于它们,结果如下:

Column A  |  Column B  | Column C
Apple     |  Apple     | Match
Orange    |  Orange    | Match
Pear      |  Banana    | Mismatch

To automate this using a python script, I tried: 要使用python脚本自动执行此操作,我尝试:

import openpyxl
wb = openpyxl.load_workbook('test.xlsx')
Sheet = wb.get_sheet_by_name('Sheet1')
for cellObj in Sheet.columns[2]:
    cellObj.value = '=IF($A$1=$B$1, "Match", "Mismatch")
wb.save('test.xlsx')

This wrote the formula to all cells in column C, however the formula only referenced cell A1 and B1, so result in all cells in column C = Match. 这将公式写入C列中的所有单元格,但公式仅引用了单元格A1和B1,因此导致列C中的所有单元格=匹配。

Column A  |  Column B  | Column C
Apple     |  Apple     | Match
Orange    |  Orange    | Match
Pear      |  Banana    | Match

How would you handle this? 你会怎么处理这个?

You probably want to make the creation of the formula dynamic so each row of C takes from the corresponding rows of A and B : 您可能希望创建公式动态,因此C每一行都取自AB的相应行:

for i, cellObj in enumerate(Sheet.columns[2], 1):
    cellObj.value = '=IF($A${0}=$B${0}, "Match", "Mismatch")'.format(i)

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

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