如何将工作表的列数作为整数(28)而不是Excel-字母(“AB”)?

时间:2010-12-30 16:08:15

标签: php phpexcel

假设:

$this->objPHPExcelReader = PHPExcel_IOFactory::createReaderForFile($this->config['file']);
$this->objPHPExcelReader->setLoadSheetsOnly(array($this->config['worksheet']));
$this->objPHPExcelReader->setReadDataOnly(true);
$this->objPHPExcel = $this->objPHPExcelReader->load($this->config['file']);

我可以遍历这样的行,但它非常慢,即在一个3MB的Excel文件中,工作表上有“EL”列,它需要每行1秒

foreach ($this->objPHPExcel->setActiveSheetIndex(0)->getRowIterator() as $row)
{
    $dataset = array();
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);
    foreach ($cellIterator as $cell)
    {
        if (!is_null($cell))
        {
            $dataset[] = $cell->getCalculatedValue();
        }
    }
    $this->datasets[] = $dataset;
}

当我像这样迭代时,它显着更快(在30秒内大约2000行),但我将不得不转换字母,例如“EL”到一个数字:

$highestColumm = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); // e.g. "EL"
$highestRow = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();

$number_of_columns = 150; // TODO: figure out how to get the number of cols as int
for ($row = 1; $row < $highestRow + 1; $row++) {
    $dataset = array();
    for ($column = 0; $column < $number_of_columns; $column++) {
        $dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCellByColumnAndRow($column, $row)->getValue();
    }
    $this->datasets[] = $dataset;
}

有没有办法将最高列作为整数(例如“28”)而不是Excel样式的字母(例如“AB”)?

8 个答案:

答案 0 :(得分:72)

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

从'A'的$ colString返回1,从'Z'返回26,从'AA'返回27,等等。

和(几乎)反向

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

从$ colNumber返回'A',从25返回'Z',从26返回'AA'等。

修改

一些有用的技巧:

工作表类有一个toArray()方法:

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

接受以下参数:

* @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

虽然它确实使用了迭代器,但是会稍慢一些

OR

利用PHP的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;
}

如果你正在处理大量的行,你可能会注意到++ $ row在$ row ++上的性能提升

答案 1 :(得分:1)

不确定您的类是否具有内置方法,但您始终可以在列索引字符串的每个字母上使用ord()函数。您当然必须减去'A'的基值,并从字符串最右侧的每个位置乘以26 ^ x。类似的东西:

    $input_string = 'BC';
    $base_value = 64;
    $decimal_value = 26;
    $column_index = 0;
    for ($i = 0; $i < strlen($input_string); $i++) {
        $char_value = ord($input_string[$i]);
        $char_value -= $base_value;
        $char_value *= pow($decimal_value, (strlen($input_string) - ($i + 1)));
        $column_index += $char_value;
    }
    echo $column_index;

基本上这会使'BC'相等(2 * 26 ^ 1)+(3 * 26 ^ 0)= 55。

$ input_string是列索引字符串,$ base_value是'A'的ord()值减1,$ decimal_value是A0的值。应该可以处理任何数字列。经过测试。希望这会有所帮助。

答案 2 :(得分:1)

这是dqhendricks答案的简化版本。我已添加到副本,一个函数假设您输入完整的Excel单元格引用(即“AB12”),另一个函数假设您只输入列引用(即“AB”)。它们都返回基于零的索引。

输入完整单元格参考

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;
}

仅输入列参考

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;
}

该函数从字符串的后面到前面以增加列的值。它使用ord()函数来获取字符的数值,然后减去字母值以给出本地列值。最后它乘以26的当前功率。

答案 3 :(得分:1)

最简单的解决方案是 $ getColumnIndexFromString = PHPExcel_Cell :: columnIndexFromString($ highestColumn);

答案 4 :(得分:1)

我建议将excel转换为数组,从空元素中清除它,然后计算列数:

protected function getColumnsCheck($file, $col_number) {
        if (strstr($file, ".xls") != false && strstr($file, ".xlsx") != false) {
            $fileType = PHPExcel_IOFactory::identify($file);
            $objReader = PHPExcel_IOFactory::createReader($fileType);
            $objPHPExcel = $objReader->load($file);
            $columns_empty = $objPHPExcel->getActiveSheet(0)->toArray()[0]; 

            $columns = array_filter($columns_empty);

            return ($col_number==count($columns));
        }
        return false;
    }

答案 5 :(得分:0)

    function getNameFromNumber($num) {//(Example 0 = A, 1 = B)
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
    return getNameFromNumber($num2 - 1) . $letter;
} else {
    return $letter;
}
}

getNameFromNumber(0)//返回A

答案 6 :(得分:0)

由于这个问题已经有 10 年的历史了,这里引用的包不再是最新的了:

以下是使用 phpspreadsheet 的方法:

$colNumber = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($colString); // e.g. 5

来源: https://phpspreadsheet.readthedocs.io/en/latest/topics/accessing-cells/

答案 7 :(得分:-2)

/**
 * 
 */
function number_to_alphabet($number) {
    $number = intval($number);
    if ($number <= 0) {
        return '';
    }
    $alphabet = '';
    while($number != 0) {
        $p = ($number - 1) % 26;
        $number = intval(($number - $p) / 26);
        $alphabet = chr(65 + $p) . $alphabet;
    }
    return $alphabet;
}

/**
 * Required PHP 5.6.
 * @see: http://php.net/manual/en/language.operators.arithmetic.php
 */
function alphabet_to_number($string) {
    $string = strtoupper($string);
    $length = strlen($string);
    $number = 0;
    $level = 1;
    while ($length >= $level ) {
        $char = $string[$length - $level];
        $c = ord($char) - 64;        
        $number += $c * (26 ** ($level-1));
        $level++;
    }
    return $number;
}

测试:

for ($x=1; $x<=1000; $x++) {
    echo 'number_to_alphabet('.$x.') = ',$y = number_to_alphabet($x),'; ';
    echo 'alphabet_to_number('.$y.') = '.alphabet_to_number($y).'; ';
    echo PHP_EOL;
}