您的位置:首页 > 编程语言 > PHP开发

phpexcel导出超过26列解决方案

2016-07-28 14:26 656 查看
原文:phpexcel导出超过26列解决方案

将列的数字序号转成字母使用,代码如下:

PHPExcel_Cell::stringFromColumnIndex($i); // 从o,1,2,3,..开始,相应返回返回 A,B,C,...Z,AA,AB,...

将列的字母转成数字序号使用,代码如下:

PHPExcel_Cell::columnIndexFromString('AA');

使用phpexcel导出excel文件的时候,发现报了一个错误,后来查询问题才发现是列数超过26列的问题。原先的代码:

//$content是一个需要导出的数组
$maxColumn = count($content[0]);
$maxRow =
count($content);
for ($i = 0; $i < $maxColumn; $i++) {
for ($j = 0; $j <
$maxRow; $j++) {

$pCoordinate = chr(65+$i) . '' . ($j + 1);

$pValue
= $content[$j][$i];

$objPHPExcel->getActiveSheet()->setCellValue($pCoordinate,
$pValue);
}
}
代码中只是将列直接转换为字母,没有考虑到超过26列的情况,超过26列后,chr(65+$i)就变成“[”符号了。

excel行列表示方式

excel的列的表示规则从A,B,C一直到Z,当超过26个字母的时候用两个字母进行表示:AA,AB,AC...AZ,BA,BB,BC...BZ...,当超过702时又是另外一个种表示方法。

行的表示就是1,2,3,4,5,6,7....这样下去。在phpexcel中要设一个单元格的值通过setCellValue方法就可以了,其中第一个参数表示列和行的拼接的值,如:A1,B1,AA1,BA1这样。

改进方法

知道这个之后,只要根据$i/26的整数部分和模部分计算出列的表示字母就可以了。当然phpexcel早就考虑到这个问题了,所以呢不用自己计算,只需要直接调用PHPExcel_Cell类中的stringFromColumnIndex方法就可以了。

/**
*
String from columnindex
*
*
@param int $pColumnIndex
Column index (base 0 !!!)
*
@return string
*/
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];
}

可以看出这个方法针对26列内,26到702列,超过702列都进行了处理,最后就是返回A、B、C、AA、AB这样的字符。对一开始的错误代码改进一下:

//$content是一个需要导出的数组
$maxColumn = count($content[0]);
$maxRow =
count($content);
for ($i = 0; $i < $maxColumn; $i++) {
for ($j = 0; $j <
$maxRow; $j++) {

$pCoordinate =
PHPExcel_Cell::stringFromColumnIndex($i) . '' . ($j + 1);

$pValue
= $content[$j][$i];

$objPHPExcel->getActiveSheet()->setCellValue($pCoordinate,
$pValue);
}
}

from: http://www.01happy.com/phpexcel-column-more-than-26/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: