溫馨提示×

PHP如何處理Excel文件并獲取數據

PHP
小億
243
2024-05-06 13:47:51
欄目: 編程語言

在PHP中處理Excel文件可以使用PHPExcel或PhpSpreadsheet這兩個庫。以下是使用PhpSpreadsheet庫處理Excel文件并獲取數據的示例代碼:

<?php
require '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庫,然后在代碼中引入庫文件。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女