PHP如何处理Excel文件并获取数据

   2024-10-20 2350
核心提示:在PHP中处理Excel文件可以使用PHPExcel或PhpSpreadsheet这两个库。以下是使用PhpSpreadsheet库处理Excel文件并获取数据的示例代

在PHP中处理Excel文件可以使用PHPExcel或PhpSpreadsheet这两个库。以下是使用PhpSpreadsheet库处理Excel文件并获取数据的示例代码:

<?phprequire 'vendor/autoload.php'; //引入PhpSpreadsheet库use PhpOffice\PhpSpreadsheet\IOFactory;// 导入Excel文件$spreadsheet = IOFactory::load('example.xlsx');$sheet = $spreadsheet->getActiveSheet();// 获取数据$data = [];foreach ($sheet->getRowIterator() as $row) {    $rowData = [];    $cellIterator = $row->getCellIterator();    $cellIterator->setIterateOnlyExistingCells(FALSE); // 忽略空单元格    foreach ($cellIterator as $cell) {        $rowData[] = $cell->getValue();    }    $data[] = $rowData;}// 输出数据echo '<pre>';print_r($data);echo '</pre>';?>

在上面的示例中,首先引入PhpSpreadsheet库,然后使用IOFactory::load方法导入Excel文件。接着遍历每一行并获取每个单元格的数据,最后输出数据。

需要注意的是,要先使用Composer安装PhpSpreadsheet库,然后在代码中引入库文件。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号