Location>code7788 >text

PHP converts shaped numbers to Excel subscripts

Popularity:940 ℃/2024-10-18 18:05:40

1. Background

In the past two days in the receipt of a demand, the need to export a class of all students of all achievements, in the final excel table processing time found that the exported columns more than 26 columns, the back of the AA and so on subscripts, so wrote a function to the number of integers to Excel corresponding subscripts.

2、Conversion function

/**
 * @Notes:convert an integer intoexcelCorresponding column labels
 * @Function int_to_chr
 * @param $index
 * @param $start
 * @return string
 * @Author gxk
 * @Date 2024/10/16
 * @Time 17:53
 */
function int_to_chr($index,$start=65) {
    $str = '';
    if($index >= 26){
        $les = $index % 26;
        $index = intval($index/26);
        $str .= int_to_chr($index-1);
        $str .= chr($start+$les);
        return $str;
    }
    return chr($start+$index).$str;
}

3、Test function

for ($i = 0; $i < 1352; $i++){
    dump($i."=>".int_to_chr($i));
}

4. Test results (not divided into screenshots)

5. Cautions

(1) Need to need to subtract one when the incoming subscript (because the start of the conversion function A:65), in the calculation of more than two strings (AA) there will be the second bit is 0 to start with, if there is no subtraction of one, there will be a deviation;

(2) When detecting, we mainly look at several key parts, whether 0 is converted to A (Fig. 1 in 4), whether the next of Z is AA (Fig. 2 in 4), whether the next of AZ is BA (Fig. 3 in 4), whether the next of ZZ is AAA (Fig. 4 in 4)