PHP

Algorithm to get the excel-like letter from a number

/**
 * Algorithm to getting a letter from a number
 * also getting the excel-like column name of a number
 *
 * example:
 *
 * 0 - 'A'
 * 25 - 'Z'
 * 26 - 'AA'
 */
function getLetterFromNumber($num)
{
	$numeric = $num % 26;
	$letter = chr(65 + $numeric);
	$num2 = (int)($num / 26);
	if ($num2 > 0)
	{
		return self::getNameFromNumber($num2 - 1) . $letter;
	}

	return $letter;
}

 

 

Using PhpSpreadsheet (PHPExcel is deprecated)

// result = 'A'
\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(1);

Note index 0 results in 'Z'

https://phpspreadsheet.readthedocs.io/en/develop/


if you use PHPExcel Library:

// result = 'A'
$columnLetter = PHPExcel_Cell::stringFromColumnIndex(0); // ZERO-based! 

and backwards:

// result = 1
$colIndex = PHPExcel_Cell::columnIndexFromString('A');
Афоризм дня:
Мудрость – царица неба и земли. (538)
PHP

Leave a reply

Яндекс.Метрика