'I am applying Max formula of excel using OpenPyXL but it is deleting formula on opening file

Please note that I am applying MAX formula in a column through OpenPyXL. The source data is also coming from Formula applied through OpenPyXL.

Problem is that it is deleting formula.

Some code given below:

#cumm profit
if(wsprofitrowno==2):
    wsprofit.cell(row=wsprofitrowno, column = 3).value = '=SUM(B2)'
else:
    
    wsprofit.cell(row=wsprofitrowno, column = 3).value = '=B%d+C%d' % (wsprofitrowno, wsprofitrowno-1)

#Peak
if(wsprofitrowno>2):       
    wsprofit.cell(row=wsprofitrowno, column = 4).value = '=MAX($C$2:C%d' % (wsprofitrowno)
    wb.save("output.xlsx")
wsprofitrowno = wsprofitrowno + 1    


Solution 1:[1]

You are trying to add this as a formula in the Excel cell '=MAX($C$2:C%d' % (wsprofitrowno) so Excel would see that as an error and the formula would be rejected. The Excel MAX function needs a closing bracket, since you are trying to use the row 'wsprofitrowno' as the row value for the second coordinate of the MAX formula you can do either

  1. Add the close bracket; '=MAX($C$2:C%d)' % wsprofitrowno
  2. just do '=MAX($C$2:C' + str(wsprofitrowno) + ')'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 moken