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

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

Given:

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


        
6条回答
  •  情书的邮戳
    2020-12-12 23:11

    $colNumber = PHPExcel_Cell::columnIndexFromString($colString);
    

    returns 1 from a $colString of 'A', 26 from 'Z', 27 from 'AA', etc.

    and the (almost) reverse

    $colString = PHPExcel_Cell::stringFromColumnIndex($colNumber);
    

    returns 'A' from a $colNumber of 0, 'Z' from 25, 'AA' from 26, etc.

    EDIT

    A couple of useful tricks:

    There is a toArray() method for the worksheet class:

    $this->datasets = $this->objPHPExcel->setActiveSheetIndex(0)->toArray();
    

    which accepts the following parameters:

    * @param  mixed    $nullValue          Value returned in the array entry if a cell doesn't exist
    * @param  boolean  $calculateFormulas  Should formulas be calculated?
    * @param  boolean  $formatData         Should formatting be applied to cell values?
    * @param  boolean  $returnCellRef      False - Return a simple array of rows and columns indexed by number counting from zero
    *                                      True - Return rows and columns indexed by their actual row and column IDs
    

    although it does use the iterators, so would be slightly slower

    OR

    Take advantage of PHP's ability to increment character strings Perl Style

    $highestColumm = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); // e.g. "EL" 
    $highestRow = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();  
    
    $highestColumm++;
    for ($row = 1; $row < $highestRow + 1; $row++) {     
        $dataset = array();     
        for ($column = 'A'; $column != $highestColumm; $column++) {
            $dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($column . $row)->getValue();
        }
        $this->datasets[] = $dataset;
    }
    

    and if you're processing a large number of rows, you might actually notice the performance improvement of ++$row over $row++

提交回复
热议问题