Openpyxl Formula filling unique row values for ent

2019-05-30 08:09发布

I'm trying to write a formula into a cell and write for the entire column. However, for each cell in the column, it reads =(E2-F2)/C2. For each cell on the same column how do I get it so reads (E3-F3)/C3 and so on?

import openpyxl

wb = openpyxl.load_workbook('yes.xlsx')
Sheet = wb.get_sheet_by_name('Sheet1')

n = '=(E2-F2)/C2'
for cellObj in list(Sheet.columns)[6]:
    cellObj.value = n
wb.save("row_creation_loop.xlsx")

2条回答
Explosion°爆炸
2楼-- · 2019-05-30 08:24

From my comment, here is the for-loop code in full:

# n = '=(E2-F2)/C2' # move this assignment into the for-loop

for row, cellObj in enumerate(list(Sheet.columns)[6]):
    print cellObj
    n = '=(E%d-F%d)/C%d' % (row, row, row)
    # print n # check that n gets assigned correct string value
    cellObj.value = n

Hope this helps.

查看更多
孤傲高冷的网名
3楼-- · 2019-05-30 08:43

you have to add +1 at the r(row, row, row).

# n = '=(E2-F2)/C2' # move this assignment into the for-loop

for row, cellObj in enumerate(list(Sheet.columns)[6]):
    print cellObj
    n = '=(E%d-F%d)/C%d' % (row, row, row)
    # print n # check that n gets assigned correct string 
查看更多
登录 后发表回答