ExcelFormula.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # -*- coding: windows-1252 -*-
  2. from . import ExcelFormulaParser, ExcelFormulaLexer
  3. import struct
  4. from .antlr import ANTLRException
  5. class Formula(object):
  6. __slots__ = ["__s", "__parser", "__sheet_refs", "__xcall_refs"]
  7. def __init__(self, s):
  8. try:
  9. self.__s = s
  10. lexer = ExcelFormulaLexer.Lexer(s)
  11. self.__parser = ExcelFormulaParser.Parser(lexer)
  12. self.__parser.formula()
  13. self.__sheet_refs = self.__parser.sheet_references
  14. self.__xcall_refs = self.__parser.xcall_references
  15. except ANTLRException as e:
  16. # print e
  17. raise ExcelFormulaParser.FormulaParseException("can't parse formula " + s)
  18. def get_references(self):
  19. return self.__sheet_refs, self.__xcall_refs
  20. def patch_references(self, patches):
  21. for offset, idx in patches:
  22. self.__parser.rpn = self.__parser.rpn[:offset] + struct.pack('<H', idx) + self.__parser.rpn[offset+2:]
  23. def text(self):
  24. return self.__s
  25. def rpn(self):
  26. '''
  27. Offset Size Contents
  28. 0 2 Size of the following formula data (sz)
  29. 2 sz Formula data (RPN token array)
  30. [2+sz] var. (optional) Additional data for specific tokens
  31. '''
  32. return struct.pack("<H", len(self.__parser.rpn)) + self.__parser.rpn