How to get the number of columns of worksheet as integer (28) instead of Excel-letters (“AB”)?

后端 未结 6 396
一生所求
一生所求 2020-12-12 22:19

Given:

$this->objPHPExcelReader = PHPExcel_IOFactory::createReaderForFile($this->config[\'file\']);
$this->objPHPExcelReader->setLoadSheetsOnly(a         


        
6条回答
  •  孤城傲影
    2020-12-12 23:17

    This is a somewhat simplified version of dqhendricks answer. I have added to copies, one function assuming you enter the full excel cell reference (ie. "AB12") and the other assuming you enter just the column reference (ie. "AB"). They both return a zero based index.

    Input Full Cell Reference

    function getIndex ($cell) {
        // Strip cell reference down to just letters
        $let = preg_replace('/[^A-Z]/', '', $cell);
    
        // Iterate through each letter, starting at the back to increment the value
        for ($num = 0, $i = 0; $let != ''; $let = substr($let, 0, -1), $i++)
            $num += (ord(substr($let, -1)) - 65) * pow(26, $i);
    
        return $num;
    }
    

    Input Column Reference Only

    function getIndex ($let) {
        // Iterate through each letter, starting at the back to increment the value
        for ($num = 0, $i = 0; $let != ''; $let = substr($let, 0, -1), $i++)
            $num += (ord(substr($let, -1)) - 65) * pow(26, $i);
    
        return $num;
    }
    

    The function goes from the back of the string to the front to increase the value of the column. It uses the ord() function to get the numeric value of a character and then has the letter value subtracted to give the local column value. Finally it is multiplied by the current power of 26.

提交回复
热议问题