PhpSpreadsheet读取excel

2022-03-03
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * @description: 读取excel
 * @param string $path 文件路径
 * @return {*} 返回生成器
 */
function readExcel($path)
{
    if (!is_file($path)) {
        throw new Exception('文件不存在');
    }
    $inputFileType = IOFactory::identify($path);
    $reader        = IOFactory::createReader($inputFileType);
    $reader->setReadDataOnly(true);
    $excel = $reader->load($path);
    $sheet = $excel->getActiveSheet();
    foreach ($sheet->getRowIterator() as $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(true);
        $data = [];
        foreach ($cellIterator as $cell) {
            $data[$cell->getColumn()] = $cell->getValue();
        }
        yield $data;
    }
}

 

{/if}