Skip to content

Instantly share code, notes, and snippets.

@digitalkreativ
Created January 20, 2023 15:33
Show Gist options
  • Save digitalkreativ/0dbac525b26361e88dfa4f4b052c9821 to your computer and use it in GitHub Desktop.
Save digitalkreativ/0dbac525b26361e88dfa4f4b052c9821 to your computer and use it in GitHub Desktop.
Calculate excel column #php

Code

Taken from: https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Cell/Coordinate.php

public static function stringFromColumnIndex($columnIndex)
{
  static $indexCache = [];

  if (!isset($indexCache[$columnIndex])) {
    $indexValue = $columnIndex;
    $base26 = null;
    do {
      $characterValue = ($indexValue % 26) ?: 26;
      $indexValue = ($indexValue - $characterValue) / 26;
      $base26 = chr($characterValue + 64) . ($base26 ?: '');
    } while ($indexValue > 0);
    $indexCache[$columnIndex] = $base26;
  }

  return $indexCache[$columnIndex];
}

Usage

stringFromColumnIndex(28)

return 'AB'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment