Okay, here's a simple example
I have created a spreadsheet with first spreadsheet "Feuil1" (french version) which contains A1,...,A7
as 1,2,3,4,5,6,7
and A8=SUM(A1:A7)
Here's the code, that could be adapted maybe to other operators. maybe not so simply. It also supports ranges from A1:B12 for instance, untested and no parsing support for cols like AA
although could be done.
import openpyxl,re
fre = re.compile(r"=(\w+)\((\w+):(\w+)\)$")
cre = re.compile(r"([A-Z]+)(\d+)")
def the_sum(a,b):
return a+b
d=dict()
d["SUM"] = the_sum
def get_evaluated_value(w,sheet_name,cell_name):
result = w[sheet_name][cell_name].value
if isinstance(result,int) or isinstance(result,float):
pass
else:
m = fre.match(result)
if m:
g = m.groups()
operator=d[g[0]] # ATM only sum is supported
# compute range
mc1 = cre.match(g[1])
mc2 = cre.match(g[2])
start_col = ord(mc1.group(1))
end_col = ord(mc2.group(1))
start_row = int(mc1.group(2))
end_row = int(mc2.group(2))
result = 0
for i in range(start_col,end_col+1):
for j in range(start_row,end_row+1):
c = chr(i)+str(j)
result = operator(result,w["Feuil1"][c].value)
return result
w = openpyxl.load_workbook(r"C:\Users\dartypc\Desktop\test.xlsx")
print(get_evaluated_value(w,"Feuil1","A2"))
print(get_evaluated_value(w,"Feuil1","A8"))
output:
2
28
yay!