phpspreadsheet:迭代方式读取 Excel 0 个改进

迭代方式读取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);
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!