1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > php 数字转换为字符串 PHP-将数字转换为Excel的字符串

php 数字转换为字符串 PHP-将数字转换为Excel的字符串

时间:2019-11-19 23:54:19

相关推荐

php 数字转换为字符串 PHP-将数字转换为Excel的字符串

我需要根据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];

}

请注意,PHPExcel方法的索引从0开始,因此您可能需要稍作调整以使A从1开始,或者递减所传递的数值

单元格对象中还有一个对应的columnIndexFromString()方法,该方法从列地址返回数字

标签:phpexcel,string,php

来源: https://codeday.me/bug/1030/1968174.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。