AddressHelper.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Cell;
  3. use PhpOffice\PhpSpreadsheet\Exception;
  4. class AddressHelper
  5. {
  6. public const R1C1_COORDINATE_REGEX = '/(R((?:\[-?\d*\])|(?:\d*))?)(C((?:\[-?\d*\])|(?:\d*))?)/i';
  7. /**
  8. * Converts an R1C1 format cell address to an A1 format cell address.
  9. */
  10. public static function convertToA1(
  11. string $address,
  12. int $currentRowNumber = 1,
  13. int $currentColumnNumber = 1
  14. ): string {
  15. $validityCheck = preg_match('/^(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))$/i', $address, $cellReference);
  16. if ($validityCheck === 0) {
  17. throw new Exception('Invalid R1C1-format Cell Reference');
  18. }
  19. $rowReference = $cellReference[2];
  20. // Empty R reference is the current row
  21. if ($rowReference === '') {
  22. $rowReference = (string) $currentRowNumber;
  23. }
  24. // Bracketed R references are relative to the current row
  25. if ($rowReference[0] === '[') {
  26. $rowReference = $currentRowNumber + (int) trim($rowReference, '[]');
  27. }
  28. $columnReference = $cellReference[4];
  29. // Empty C reference is the current column
  30. if ($columnReference === '') {
  31. $columnReference = (string) $currentColumnNumber;
  32. }
  33. // Bracketed C references are relative to the current column
  34. if (is_string($columnReference) && $columnReference[0] === '[') {
  35. $columnReference = $currentColumnNumber + (int) trim($columnReference, '[]');
  36. }
  37. if ($columnReference <= 0 || $rowReference <= 0) {
  38. throw new Exception('Invalid R1C1-format Cell Reference, Value out of range');
  39. }
  40. $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference;
  41. return $A1CellReference;
  42. }
  43. protected static function convertSpreadsheetMLFormula(string $formula): string
  44. {
  45. $formula = substr($formula, 3);
  46. $temp = explode('"', $formula);
  47. $key = false;
  48. foreach ($temp as &$value) {
  49. // Only replace in alternate array entries (i.e. non-quoted blocks)
  50. if ($key = !$key) {
  51. $value = str_replace(['[.', ':.', ']'], ['', ':', ''], $value);
  52. }
  53. }
  54. unset($value);
  55. return implode('"', $temp);
  56. }
  57. /**
  58. * Converts a formula that uses R1C1/SpreadsheetXML format cell address to an A1 format cell address.
  59. */
  60. public static function convertFormulaToA1(
  61. string $formula,
  62. int $currentRowNumber = 1,
  63. int $currentColumnNumber = 1
  64. ): string {
  65. if (substr($formula, 0, 3) == 'of:') {
  66. // We have an old-style SpreadsheetML Formula
  67. return self::convertSpreadsheetMLFormula($formula);
  68. }
  69. // Convert R1C1 style references to A1 style references (but only when not quoted)
  70. $temp = explode('"', $formula);
  71. $key = false;
  72. foreach ($temp as &$value) {
  73. // Only replace in alternate array entries (i.e. non-quoted blocks)
  74. if ($key = !$key) {
  75. preg_match_all(self::R1C1_COORDINATE_REGEX, $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
  76. // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
  77. // through the formula from left to right. Reversing means that we work right to left.through
  78. // the formula
  79. $cellReferences = array_reverse($cellReferences);
  80. // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
  81. // then modify the formula to use that new reference
  82. foreach ($cellReferences as $cellReference) {
  83. $A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber);
  84. $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
  85. }
  86. }
  87. }
  88. unset($value);
  89. // Then rebuild the formula string
  90. return implode('"', $temp);
  91. }
  92. /**
  93. * Converts an A1 format cell address to an R1C1 format cell address.
  94. * If $currentRowNumber or $currentColumnNumber are provided, then the R1C1 address will be formatted as a relative address.
  95. */
  96. public static function convertToR1C1(
  97. string $address,
  98. ?int $currentRowNumber = null,
  99. ?int $currentColumnNumber = null
  100. ): string {
  101. $validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference);
  102. if ($validityCheck === 0) {
  103. throw new Exception('Invalid A1-format Cell Reference');
  104. }
  105. $columnId = Coordinate::columnIndexFromString($cellReference['col_ref']);
  106. if ($cellReference['absolute_col'] === '$') {
  107. // Column must be absolute address
  108. $currentColumnNumber = null;
  109. }
  110. $rowId = (int) $cellReference['row_ref'];
  111. if ($cellReference['absolute_row'] === '$') {
  112. // Row must be absolute address
  113. $currentRowNumber = null;
  114. }
  115. if ($currentRowNumber !== null) {
  116. if ($rowId === $currentRowNumber) {
  117. $rowId = '';
  118. } else {
  119. $rowId = '[' . ($rowId - $currentRowNumber) . ']';
  120. }
  121. }
  122. if ($currentColumnNumber !== null) {
  123. if ($columnId === $currentColumnNumber) {
  124. $columnId = '';
  125. } else {
  126. $columnId = '[' . ($columnId - $currentColumnNumber) . ']';
  127. }
  128. }
  129. $R1C1Address = "R{$rowId}C{$columnId}";
  130. return $R1C1Address;
  131. }
  132. }