<?php
// 引入 PHPExcel 类库
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
// 定义 Excel 文件路径
$excelFile = 'example.xlsx';
try {
// 读取 Excel 文件
$spreadsheet = IOFactory::load($excelFile);
// 获取工作表
$worksheet = $spreadsheet->getActiveSheet();
// 获取所有行数据
$data = [];
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // 这将循环遍历所有单元格,即使它们是空的
$rowData = [];
foreach ($cellIterator as $cell) {
$rowData[] = $cell->getValue();
}
$data[] = $rowData;
}
// 打印读取的数据
print_r($data);
} catch (Exception $e) {
echo '读取 Excel 文件时出错: ', $e->getMessage(), "\n";
}
?>
require 'vendor/autoload.php';
来引入 PHPExcel 类库。确保你已经通过 Composer 安装了 phpoffice/phpspreadsheet
。$excelFile = 'example.xlsx';
。IOFactory::load($excelFile)
方法来加载 Excel 文件。getActiveSheet()
方法获取当前活动的工作表。getRowIterator()
和 getCellIterator()
方法遍历每一行和每个单元格,获取单元格的值并存储到数组中。print_r($data);
打印读取的数据。如果你没有安装 phpoffice/phpspreadsheet
,可以通过 Composer 安装:
composer require phpoffice/phpspreadsheet
上一篇:php 数组追加
下一篇:php 写文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站