[英]Converting a number to a string for excel
I need to convert an integer (number of columns) into a string according to excel column naming scheme, like so: 我需要根据excel列命名方案将整数(列数)转换为字符串,如下所示:
1 => A
2 => B
25 => Z
26 => AA
28 => AC
51 => BA
Do you know of a smart and painless way to do this within php, or should I go about writing my own custom function? 你知道在php中做一个聪明而无痛的方法吗,还是我应该编写自己的自定义函数?
You can do it with a simple loop: 你可以用一个简单的循环来做到这一点:
$number = 51;
$letter = 'A';
for ($i = 1; $i <= $number; ++$i) {
++$letter;
}
echo $letter;
though if you're doing this frequently with higher values, it'll be a bit slow 虽然如果你经常用更高的值做这件事,它会有点慢
or look at the stringFromColumnIndex() method in PHPExcel's Cell object that is used for exactly this purpose 或者查看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];
}
Note that the PHPExcel method indexes from 0, so you might need to adjust it slightly to give A from 1, or decrement the numeric value that you pass 请注意,PHPExcel方法的索引从0开始,因此您可能需要稍微调整它以使A从1开始,或者递减您传递的数值
There is also a corresponding columnIndexFromString() method in the cell object that returns a numeric from a column address 单元对象中还有一个对应的columnIndexFromString()方法,它从列地址返回一个数字
It can also be done quite easily with pure PHP: 使用纯PHP也可以很容易地完成它:
function getCellFromColnum($colNum) {
return ($colNum < 26 ? chr(65+$colNum) : chr(65+floor($colNum/26)-1) . chr(65+ ($colNum % 26)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.