python写入excel公式_使用Python将公式写入Excel

1586010002-jmsa.png

I am in the process of brain storming how to best tackle the below problem. Any input is greatly appreciated.

Sample Excel sheet columns:

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")

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:

Column A | Column B | Column C

Apple | Apple | Match

Orange | Orange | Match

Pear | Banana | Mismatch

To automate this using a python script, I tried:

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.

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:

for i, cellObj in enumerate(Sheet.columns[2], 1):

cellObj.value = '=IF($A${0}=$B${0}, "Match", "Mismatch")'.format(i)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值