PHPExcel-如何逐行读取Excel工作表 [英] PHPExcel - How can i read the Excel sheet row by row

查看:776
本文介绍了PHPExcel-如何逐行读取Excel工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PHPExcel逐行读取Excel工作表?我的工作表包含超过100000行,但我只想读取500行.

How can i read Excel worksheet row by row using PHPExcel? I have a sheet contains more than 100000 rows, but i want to read only 500 rows.

$sheetData = $objPHPExcel->getActiveSheet();
$highestRow = $sheetData->getHighestRow(); 
$highestColumn = $sheetData->getHighestColumn(); 
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 

echo '<table>';
for ($row = 1; $row <= $highestRow; ++$row) {
    echo '<tr>';

    for ($col = 0; $col <= $highestColumnIndex; ++$col) {
    echo '<td>' . $sheetData->getCellByColumnAndRow($col, $row)->getValue() . '</td>';
    }

    echo '</tr>';
}
echo '</table>';

推荐答案

如果您只想 读取 500行,则只需 load 使用读取过滤器读取500行:

If you only want to read 500 rows, then only load 500 rows using a read filter:

$inputFileType = 'Excel5';
$inputFileName = './sampleData/example2.xls';


/**  Define a Read Filter class implementing PHPExcel_Reader_IReadFilter  */
class myReadFilter implements PHPExcel_Reader_IReadFilter
{
    private $_startRow = 0;

    private $_endRow = 0;

    /**  Set the list of rows that we want to read  */
    public function setRows($startRow, $chunksize) {
        $this->_startRow    = $startRow;
        $this->_endRow      = $startRow + $chunkSize;
    }

    public function readCell($column, $row, $worksheetName = '') {
        //  Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
        if (($row >= $this->_startRow && $row < $this->_endRow)) {
            return true;
        }
        return false;
    }
}


/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);


/**  Define how many rows we want to read for each "chunk"  **/
$chunkSize = 500;
/**  Create a new Instance of our Read Filter  **/
$chunkFilter = new myReadFilter();

/**  Tell the Reader that we want to use the Read Filter that we've Instantiated  **/
$objReader->setReadFilter($chunkFilter);

/**  Tell the Read Filter, the limits on which rows we want to read this iteration  **/
$chunkFilter->setRows(1,500);
/**  Load only the rows that match our filter from $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

有关读取过滤器的更多详细信息,请参见/Documentation中的PHPExcel User Documentation - Reading Spreadsheet Files文档

See the PHPExcel User Documentation - Reading Spreadsheet Files document in /Documentation for more details on Read Filters

这篇关于PHPExcel-如何逐行读取Excel工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆