点击(此处)折叠或打开
-
while ( true ) {
-
$data = $this->iteration_excel($result['msg']['excel_path'],$result['msg']['excel_type'],$start_row,$chunk_size);
-
//处理业务逻辑
- if( empty($data) ) {
-
break;
}
- }
根据迭代器调用指定行
点击(此处)折叠或打开
-
/**
-
* 迭代excel
-
* $excel_path excel路径
-
* $excel_type 模板类型
-
* $start_row 开始行
-
* $chunk_size 步长
-
*/
-
private function iteration_excel($excel_path,$excel_type,$start_row,$chunk_size) {
-
try {
-
//自动检测excel 类型
-
$inputFileType = PHPExcel_IOFactory::identify($excel_path);
-
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
-
-
//初始化excel过滤器
-
$chunkFilter = new chunkReadFilter();
-
$chunkFilter->setRows($start_row, $chunk_size);
-
$objReader->setReadFilter($chunkFilter);
-
-
$objPHPExcel = $objReader->load($excel_path);
-
$objPHPExcel->setActiveSheetIndex(0);
-
$activeSheet = $objPHPExcel->getActiveSheet();
-
$data = array();
-
$endRow = $start_row + $chunk_size;
-
-
$highestColumn = ($excel_type == 0) ? 'I':'F';
-
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
-
for ($row = $start_row; $row < $endRow; $row++) {
-
for ($col = 0; $col < $highestColumnIndex; $col++) {
-
$data[$row][] = (string) $activeSheet->getCellByColumnAndRow($col, $row)->getValue();
-
}
-
if(implode($data[$row], '') == '') {
-
unset($data[$row]);
-
break;
-
}
-
}
-
return $data;
-
} catch( Exception $e ){
-
response ( "excel读取失败", 201, '' );
-
}
- }
实现PHPExcel_Reader_IReadFilter 迭代器类
点击(此处)折叠或打开
-
/**
-
* 分块读取EXCEL
-
* Class chunkReadFilter
-
*/
-
-
class chunkReadFilter implements PHPExcel_Reader_IReadFilter
-
{
-
private $_startRow = 0; // 开始行
-
private $_endRow = 0; // 结束行
-
-
-
// 定义了一个读去指定范围行的方法
-
public function setRows($startRow, $chunkSize) {
-
$this->_startRow = $startRow;
-
$this->_endRow = $startRow + $chunkSize;
-
}
-
public function readCell($column, $row, $worksheetName = '') {
-
if ( $row >= $this->_startRow && $row < $this->_endRow) {
-
return true;
-
}
-
return false;
-
}
- }