PHPExcel 输入上一列输出下一列

荆轲刺秦王

简单介绍一下此函数实现的效果,大家都知道 PHPExcel 的列 是由 "A","B","C"...."Z","AA","AB"....."AZ","BA"......

function get_excel_title($ColumnIndex = ''){
	static $_indexCache = array();
	if(empty($ColumnIndex)){
		$ColumnIndex = 'A';
	}
	if(strlen($ColumnIndex) == 1){
		$a = ord($ColumnIndex);
		$pColumnIndex = $a+1-65;
	}else if(strlen($ColumnIndex) == 2){
		$arr = str_split($ColumnIndex);
		$b = $arr[0];
		$c = ord($b);
		$q = $c-64;
		$d = $arr[1];
		$f = ord($d);
		$e = $f - 65;
		$pColumnIndex = $q * 26 + $e + 1;
	}
	
	if (!isset($_indexCache[$pColumnIndex])) {
        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];
}

这个函数的也是有局限性的,它的最大长度是 702 ,为什么是 702 呢,是因为 'A'-'Z' 有26位,从 "AA"-"ZZ"有 676 位,26+676=702位,换句话说,就是最大长度只能到 "ZZ",是没有三位("AAA,"AAB")的。这个函数借鉴了网上前辈们的经验。

下面把前辈的代码放上来,前辈的功能是通过传入一个 值,获取它对应的 Excel 的列,例如,传入26,就会得到26在Excel中对应的值:"Z", 传入27,就可以得到 "AA",以此类推,下面我将前辈的代码放上来:

/**
 * 	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];
}

 

你可能感兴趣的:(thinkphp,PHPExcel)