phpspreadsheet:迭代方式读取 Excel
迭代方式读取excel
定义实现类
class ExcelService
{
protected $file;
/**
* @var \PhpOffice\PhpSpreadsheet\Reader\IReader
*/
private $handler;
public function create($file)
{
$this->handler = IOFactory::createReader('Xlsx');
$this->file = $file;
return $this;
}
public function read($closure, $skip = 0)
{
$this->handler->setReadDataOnly(true);
$spreadsheet = $this->handler->load($this->file);
$worksheet = $spreadsheet->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
if ($skip > 0) {
$skip--;
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$row = [];
foreach ($cellIterator as $k => $item) {
$row[$k] = $item->getValue();
}
$closure($row);
}
}
}
调用
(new ExcelService)->create($uploadFilePath)->read(function ( $excel){
//获取数据 $excel['B']
}, 2);
推荐文章: