Using result of formula in another calculation

≡放荡痞女 提交于 2020-01-06 15:42:10

问题


I would like to use the value calculated in the second, "for i in range" statement to calculate a new value using the fourth, "for i in range" statement; however, I receive the error: "could not convert string to float: 'E2*37.5'"

How do I call upon the numerical value calculated in, sheet['F{}',format(i)] ='E{}*37.5'.format(i) instead of the formula/string?

import openpyxl


wb = openpyxl.load_workbook('camdatatest.xlsx', read_only= False, data_only = True)

# Assuming you are working with Sheet1
sheet = wb['Sheet1']

for i in range(2,80):
    sheet['D{}'.format(i)] = '=C{}/3'.format(i)
for i in range(2,80):
    sheet['F{}'.format(i)] = '=E{}*37.5'.format(i)
for i in range(2,80):
    sheet['H{}'.format(i)] = '=D{}*G2*50'.format(i) 
for i in range(2,80):
    sheet['I{}'.format(i)].value = float(sheet['F{}'.format(i)].value)/float(sheet['H{}'.format(i)].value)



wb.save('camdatatestoutput.xlsx' , data_only= True)

回答1:


Unfortunately that's not quite possible because

openpyxl never evaluates formula

There are other libraries that may do so. However your problem can be overcome by recognizing that you can use yet another cell reference instead of the calculated value here.

for i in range(2,80):
    sheet['I{}'.format(i)] = '=E{}*37.5/H{}'.format(i,i)

Note that you can't set the value for the Ix cell because you don't actually have a value for the Ex or Hx cells. (well you might have but it's not clear from your question if you do)



来源:https://stackoverflow.com/questions/41449712/using-result-of-formula-in-another-calculation

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