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/20191030/1968174.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值