根据输入的数量生成符合EXCEL列标的数组

来源:互联网 发布:java判断是否有双引号 编辑:程序博客网 时间:2024/06/05 10:24

在使用PHPEXCEL导出数据库的数据到EXECL文件的时候,可以根据当前数据的字段数量,生成符合excel规则的列标

变量名起的有点随意,见谅

demo:
输出结果
代码如下:

<?php     //目前只支持 A ~ ZZ num <= 702    $num = isset($_GET['num']) ? $_GET['num'] : '';    if(empty($num)){        echo '请输入数量<br/>';        echo '示例: http://localhost/excel.php?num=100';    }elseif($num > 702){        echo '暂时最大只支持到702';    }else{        $arr = get_field($num);        echo '<pre>';        print_r($arr);    }    function get_field($num)    {             $index = ceil(($num - 26) / 26);        $a = [];        for ($i = 1; $i <= $index; $i++) {            $arr = get_excel_field(26 * $i);            $a = array_merge($a, $arr);        }        $final = get_excel_field($num);        $a = array_merge($a, $final);        return $a;    }//根据字段的数量,生成符合EXCEL规则的列号    function get_excel_field($num)    {        if (empty($num)) {            return false;        }        $index = intval($num / 26); //整数部分        $offset = $num % 26; //余数部分        //获取基础字母表        for ($i = 65; $i < 91; $i++) {            $ab[] = strtoupper(chr($i));        }        if ($num == 26) return $ab;        $start = 65;        if ($index < 1) {            $end = $start + $offset;            for ($i = $start; $i < $end; $i++) {                $arr[] = strtoupper(chr($i));            }        } else {            if ($offset == 0) {                $offset = 26;                $index = $index - 1;            }            $a = get_excel_field($offset);            $c = get_excel_field($index);            for ($t = $index - 1; $t < $index; $t++) {                for ($i = 0; $i < $offset; $i++) {                    $arr[] = $c[$t] . $a[$i];                }            }        }        return $arr;    } ?>
原创粉丝点击