PHPExcel get column name relative to given column

raidzero picture raidzero · Feb 28, 2013 · Viewed 23.7k times · Source

Using PHPExcel, is it possible to get the name of a column located X number of columns to the left or right?

Example, given column BZ, I'd like to return column name CB or BX. (2 to the right or left)

Thanks

Answer

Mark Baker picture Mark Baker · Mar 1, 2013

There are functions already built into PHPExcel to help you do this

$adjustment = -2;
$currentColumn = 'BZ';

$columnIndex = PHPExcel_Cell::columnIndexFromString($currentColumn);
$adjustedColumnIndex = $columnIndex + $adjustment;
$adjustedColumn = PHPExcel_Cell::stringFromColumnIndex($adjustedColumnIndex - 1);

Note the (historic) discrepancy that columnIndexFromString() will return a 1 for column A, but that stringFromColumnIndex expects a 0 to correspond to column A