PHPExcel - 如何逐行读取 Excel 工作表

标签 php phpexcel

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

$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 行,则使用读取过滤器仅加载 500 行:

$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 用户文档 - 读取电子表格文件 文档

关于PHPExcel - 如何逐行读取 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056030/

相关文章:

PHPExcel 无法打开文件

PHPExcel 设置单元格的边框颜色

php - 如何将 PHPExcel 生成的文件从 PHP 页面传递到另一个 PHP 页面?

php - 在 wordpress 核心中加载 css 和 js 文件

php - fatal error : Can't use function return value in write context in

PHP PDO 类连接

PHPExcel 错误 : Array and string offset access syntax with curly braces is deprecated

php - 根据标题将csv数据导入数据库

php - 表输出 php 和 mysql 没有得到结果

php - 未能删除缓冲区。没有要删除的缓冲区