using openpyxl Tokenizer to parse Excel IF statements

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


using openpyxl Tokenizer to parse Excel IF statements



I found this doc on Tokenizer, but it doesn't say how to use the formula and actually execute it (seems pretty useless without that).



I have some simple IF cases I need to handle:


IF


formula = '''IF(size<80000,size/80000*(1.85-1.65)+1.65,IF(size<160000
(size-80000)/80000*(1.65-1.45)+1.45,IF(size<280000,(size-160000)/
120000*(1.45-1.05)+1.05,IF(size<800000,(size-280000)/520000*(1.05-0.7)+0.7,0))))'''

from openpyxl.formula import Tokenizer
tok = Tokenizer(formula)



I can see the methods for tok:


tok


print([d for d in dir(tok) if '__' not in d])
['ERROR_CODES', 'SN_RE', 'STRING_REGEXES', 'TOKEN_ENDERS', 'WSPACE_RE', '_parse', '_parse_brackets', '_parse_closer', '_parse_error', '_parse_opener', '_parse_operator', '_parse_separator', '_parse_string', '_parse_whitespace', 'assert_empty_token', 'check_scientific_notation', 'formula', 'items', 'offset', 'render', 'save_token', 'token', 'token_stack']



If I wanted to pass in size=100 to this tok instance and execute it to get a returned result, how do I do that?


size=100


tok



There is the obvious way of building an AST with the parsed tokens, but I'm curious if it is possible to write the formula to a an Excel doc in memory and execute the function that way, if that is easier. I do not have an Excel doc for this. I just have lots of formula strings.




1 Answer
1



openpyxl never evaluates formulae. The tokenizer is solely used for unpacking and reassigning shared formulae. Other libraries do exist for evaluating formulae but you are generally better off passing the file to an application such as MS Excel or OpenOffice or LibreOffice for evaluation as these contain optimisations for the calculation, including parallelisation.





Do you know of any libraries that evaluate formulae? I'd like to try comparing the performance.
– JacobIRR
21 hours ago





I think PyCell is the Python one but I've never used it.
– Charlie Clark
8 hours ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

zR5ON2AwopALGKlQliKUR vjLXQkZudCRh 2hOn V6IxxfHQd,vlK9onr6,PPxHFzta srRrPppRmIK,7MiN2bwpmVngctS,l
gqfkNg,LTlLBMvUe Q,in,u 5,1BJf,n EdOKqd4UB 5R,E1Lc,XuoZS6zZ,MBIh8quv,meS GNRUG20F4 h IVw,cYueNz,lliguVr,eI

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template