| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\OpenSpout\Writer\Common\Helper; |
| 4 |
|
| 5 |
/** |
| 6 |
* This class provides helper functions when working with cells. |
| 7 |
*/ |
| 8 |
class CellHelper |
| 9 |
{ |
| 10 |
/** @var array Cache containing the mapping column index => column letters */ |
| 11 |
private static $columnIndexToColumnLettersCache = []; |
| 12 |
/** |
| 13 |
* Returns the column letters (base 26) associated to the base 10 column index. |
| 14 |
* Excel uses A to Z letters for column indexing, where A is the 1st column, |
| 15 |
* Z is the 26th and AA is the 27th. |
| 16 |
* The mapping is zero based, so that 0 maps to A, B maps to 1, Z to 25 and AA to 26. |
| 17 |
* |
| 18 |
* @param int $columnIndexZeroBased The Excel column index (0, 42, ...) |
| 19 |
* |
| 20 |
* @return string The associated cell index ('A', 'BC', ...) |
| 21 |
*/ |
| 22 |
public static function getColumnLettersFromColumnIndex($columnIndexZeroBased) |
| 23 |
{ |
| 24 |
$originalColumnIndex = $columnIndexZeroBased; |
| 25 |
// Using isset here because it is way faster than array_key_exists... |
| 26 |
if (!isset(self::$columnIndexToColumnLettersCache[$originalColumnIndex])) { |
| 27 |
$columnLetters = ''; |
| 28 |
$capitalAAsciiValue = \ord('A'); |
| 29 |
do { |
| 30 |
$modulus = $columnIndexZeroBased % 26; |
| 31 |
$columnLetters = \chr($capitalAAsciiValue + $modulus) . $columnLetters; |
| 32 |
// substracting 1 because it's zero-based |
| 33 |
$columnIndexZeroBased = (int) ($columnIndexZeroBased / 26) - 1; |
| 34 |
} while ($columnIndexZeroBased >= 0); |
| 35 |
self::$columnIndexToColumnLettersCache[$originalColumnIndex] = $columnLetters; |
| 36 |
} |
| 37 |
return self::$columnIndexToColumnLettersCache[$originalColumnIndex]; |
| 38 |
} |
| 39 |
} |
| 40 |
|