translate.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. """
  2. This module contains code to translate formulae across cells in a worksheet.
  3. The idea is that if A1 has formula "=B1+C1", then translating it to cell A2
  4. results in formula "=B2+C2". The algorithm relies on the formula tokenizer
  5. to identify the parts of the formula that need to change.
  6. """
  7. import re
  8. from .tokenizer import Tokenizer, Token
  9. from openpyxl.utils import (
  10. coordinate_to_tuple,
  11. column_index_from_string,
  12. get_column_letter
  13. )
  14. class TranslatorError(Exception):
  15. """
  16. Raised when a formula can't be translated across cells.
  17. This error arises when a formula's references would be translated outside
  18. the worksheet's bounds on the top or left. Excel represents these
  19. situations with a #REF! literal error. E.g., if the formula at B2 is
  20. '=A1', attempting to translate the formula to B1 raises TranslatorError,
  21. since there's no cell above A1. Similarly, translating the same formula
  22. from B2 to A2 raises TranslatorError, since there's no cell to the left of
  23. A1.
  24. """
  25. class Translator:
  26. """
  27. Modifies a formula so that it can be translated from one cell to another.
  28. `formula`: The str string to translate. Must include the leading '='
  29. character.
  30. `origin`: The cell address (in A1 notation) where this formula was
  31. defined (excluding the worksheet name).
  32. """
  33. def __init__(self, formula, origin):
  34. # Excel errors out when a workbook has formulae in R1C1 notation,
  35. # regardless of the calcPr:refMode setting, so I'm assuming the
  36. # formulae stored in the workbook must be in A1 notation.
  37. self.row, self.col = coordinate_to_tuple(origin)
  38. self.tokenizer = Tokenizer(formula)
  39. def get_tokens(self):
  40. "Returns a list with the tokens comprising the formula."
  41. return self.tokenizer.items
  42. ROW_RANGE_RE = re.compile(r"(\$?[1-9][0-9]{0,6}):(\$?[1-9][0-9]{0,6})$")
  43. COL_RANGE_RE = re.compile(r"(\$?[A-Za-z]{1,3}):(\$?[A-Za-z]{1,3})$")
  44. CELL_REF_RE = re.compile(r"(\$?[A-Za-z]{1,3})(\$?[1-9][0-9]{0,6})$")
  45. @staticmethod
  46. def translate_row(row_str, rdelta):
  47. """
  48. Translate a range row-snippet by the given number of rows.
  49. """
  50. if row_str.startswith('$'):
  51. return row_str
  52. else:
  53. new_row = int(row_str) + rdelta
  54. if new_row <= 0:
  55. raise TranslatorError("Formula out of range")
  56. return str(new_row)
  57. @staticmethod
  58. def translate_col(col_str, cdelta):
  59. """
  60. Translate a range col-snippet by the given number of columns
  61. """
  62. if col_str.startswith('$'):
  63. return col_str
  64. else:
  65. try:
  66. return get_column_letter(
  67. column_index_from_string(col_str) + cdelta)
  68. except ValueError:
  69. raise TranslatorError("Formula out of range")
  70. @staticmethod
  71. def strip_ws_name(range_str):
  72. "Splits out the worksheet reference, if any, from a range reference."
  73. # This code assumes that named ranges cannot contain any exclamation
  74. # marks. Excel refuses to create these (even using VBA), and
  75. # complains of a corrupt workbook when there are names with
  76. # exclamation marks. The ECMA spec only states that named ranges will
  77. # be of `ST_Xstring` type, which in theory allows '!' (char code
  78. # 0x21) per http://www.w3.org/TR/xml/#charsets
  79. if '!' in range_str:
  80. sheet, range_str = range_str.rsplit('!', 1)
  81. return sheet + "!", range_str
  82. return "", range_str
  83. @classmethod
  84. def translate_range(cls, range_str, rdelta, cdelta):
  85. """
  86. Translate an A1-style range reference to the destination cell.
  87. `rdelta`: the row offset to add to the range
  88. `cdelta`: the column offset to add to the range
  89. `range_str`: an A1-style reference to a range. Potentially includes
  90. the worksheet reference. Could also be a named range.
  91. """
  92. ws_part, range_str = cls.strip_ws_name(range_str)
  93. match = cls.ROW_RANGE_RE.match(range_str) # e.g. `3:4`
  94. if match is not None:
  95. return (ws_part + cls.translate_row(match.group(1), rdelta) + ":"
  96. + cls.translate_row(match.group(2), rdelta))
  97. match = cls.COL_RANGE_RE.match(range_str) # e.g. `A:BC`
  98. if match is not None:
  99. return (ws_part + cls.translate_col(match.group(1), cdelta) + ':'
  100. + cls.translate_col(match.group(2), cdelta))
  101. if ':' in range_str: # e.g. `A1:B5`
  102. # The check is necessarily general because range references can
  103. # have one or both endpoints specified by named ranges. I.e.,
  104. # `named_range:C2`, `C2:named_range`, and `name1:name2` are all
  105. # valid references. Further, Excel allows chaining multiple
  106. # colons together (with unclear meaning)
  107. return ws_part + ":".join(
  108. cls.translate_range(piece, rdelta, cdelta)
  109. for piece in range_str.split(':'))
  110. match = cls.CELL_REF_RE.match(range_str)
  111. if match is None: # Must be a named range
  112. return range_str
  113. return (ws_part + cls.translate_col(match.group(1), cdelta)
  114. + cls.translate_row(match.group(2), rdelta))
  115. def translate_formula(self, dest=None, row_delta=0, col_delta=0):
  116. """
  117. Convert the formula into A1 notation, or as row and column coordinates
  118. The formula is converted into A1 assuming it is assigned to the cell
  119. whose address is `dest` (no worksheet name).
  120. """
  121. tokens = self.get_tokens()
  122. if not tokens:
  123. return ""
  124. elif tokens[0].type == Token.LITERAL:
  125. return tokens[0].value
  126. out = ['=']
  127. # per the spec:
  128. # A compliant producer or consumer considers a defined name in the
  129. # range A1-XFD1048576 to be an error. All other names outside this
  130. # range can be defined as names and overrides a cell reference if an
  131. # ambiguity exists. (I.18.2.5)
  132. if dest:
  133. row, col = coordinate_to_tuple(dest)
  134. row_delta = row - self.row
  135. col_delta = col - self.col
  136. for token in tokens:
  137. if (token.type == Token.OPERAND
  138. and token.subtype == Token.RANGE):
  139. out.append(self.translate_range(token.value, row_delta,
  140. col_delta))
  141. else:
  142. out.append(token.value)
  143. return "".join(out)