使用phpexcel从特定范围的单元格中读取值

时间:2014-01-14 13:50:18

标签: php phpexcel

我对PHPExcel很新。我想要做的是从下面的excel电子表格中读取一些单元格是一个示例电子表格,突出显示的部分显示要阅读的部分 excel spreadsheet example

我已经做了一些必要的初始化:

  $objPHPExcel = PHPExcel_IOFactory::load($filename); 

任何建议都会有所帮助,谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用Worksheet的rangeToArray()方法将一系列单元格的内容传输到PHP数组:

$myDataArray = $objPHPExcel->getActiveSheet()->rangeToArray('B4:N7', NULL, True, True);

该方法的参数是:

 * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
 * @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

答案 1 :(得分:2)

我已经找到了解决问题的方法......

$objReader = new PHPExcel_Reader_Excel2007();
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename); // load filename into PHPExcel object
        $objPHPExcel->setActiveSheetIndexByName('CA1');
        $objWorksheet = $objPHPExcel->getActiveSheet();

        $row_index = $objWorksheet->getHighestRow(); // e.g. 5
        $col_name = $objWorksheet->getHighestColumn(); // e.g. B
        $col_index = PHPExcel_Cell::columnIndexFromString($col_name); // e.g. 1 (which is equivalent to B)


        for($row =4; $row <= $row_index; $row++){                
            for($col=1; $col<=$col_index; $col++){
                echo $objWorksheet->getCellByColumnAndRow($col, $row)->getValue().' ';
            }
            echo '<br>';
        }