Openpyxl Formula filling unique row values for entire column

南楼画角 提交于 2019-12-08 08:09:52

问题


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

回答1:


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.




回答2:


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 


来源:https://stackoverflow.com/questions/45948778/openpyxl-formula-filling-unique-row-values-for-entire-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!