我需要将一个整数(列数)转换为字符串,按照Excel列命名方案进行命名,如下所示:
1 => A
2 => B
25 => Z
26 => AA
28 => AC
51 => BA
你知道在php中有没有聪明而无痛的方法来完成这个操作,或者我应该编写自己的自定义函数?
$number = 51;
$letter = 'A';
for ($i = 1; $i <= $number; ++$i) {
++$letter;
}
echo $letter;
如果您经常使用较高的值,这样做会有点慢。
或者查看PHPExcel的Cell对象中的stringFromColumnIndex()方法,该方法专门用于此目的。
public static function stringFromColumnIndex($pColumnIndex = 0) {
// Using a lookup cache adds a slight memory overhead, but boosts speed
// caching using a static within the method is faster than a class static,
// though it's additional memory overhead
static $_indexCache = array();
if (!isset($_indexCache[$pColumnIndex])) {
// Determine column string
if ($pColumnIndex < 26) {
$_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex);
} elseif ($pColumnIndex < 702) {
$_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) .
chr(65 + $pColumnIndex % 26);
} else {
$_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) .
chr(65 + ((($pColumnIndex - 26) % 676) / 26)) .
chr(65 + $pColumnIndex % 26);
}
}
return $_indexCache[$pColumnIndex];
}
function getCellFromColnum($colNum) {
return ($colNum < 26 ? chr(65+$colNum) : chr(65+floor($colNum/26)-1) . chr(65+ ($colNum % 26)));
}