PHP 中的 Excel 操作:PhpSpreadsheet 和 PhpOffice 库
在现代 Web 开发中,经常需要将数据导出为 Excel 格式、导入报表或在服务器端处理表格。PHP 提供了几个强大的库来处理 .xlsx、.xls 和 .ods 文件。本文将详细介绍 PhpSpreadsheet——一个现代且活跃开发的库,它已取代了过时的 PHPExcel。
什么是 PhpSpreadsheet?
PhpSpreadsheet 是一个用于读取、写入和编辑多种格式电子表格的库:Excel、OpenDocument、CSV、HTML 和 PDF。它使用纯 PHP 编写,无需安装额外扩展(除了标准的 zip 和 xml),并支持 Excel 的所有主要功能:样式、公式、图表、条件格式、多个工作表等。
安装
通过 Composer 安装:
composer require phpoffice/phpspreadsheet安装后,项目中会出现包含自动加载功能的 vendor 文件夹。开始使用前,只需引入自动加载器:
require 'vendor/autoload.php';
use PhpOffice\\PhpSpreadsheet\\Spreadsheet;use PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;创建一个简单的 Excel 文件
来看一个基本示例:创建一个包含标题和几行数据的文件。
// 创建一个新的 Spreadsheet 对象$spreadsheet = new Spreadsheet();$sheet = $spreadsheet->getActiveSheet();
// 设置标题$sheet->setCellValue('A1', '姓名') ->setCellValue('B1', '邮箱') ->setCellValue('C1', '注册日期');
// 填充数据$sheet->setCellValue('A2', '伊万·伊万诺夫') ->setCellValue('B2', 'ivan@example.com') ->setCellValue('C2', '2024-01-15');
$sheet->setCellValue('A3', '玛丽亚·彼得罗娃') ->setCellValue('B3', 'maria@example.com') ->setCellValue('C3', '2024-02-20');
// 保存文件$writer = new Xlsx($spreadsheet);$writer->save('users.xlsx');
echo "文件 users.xlsx 创建成功!";运行脚本后,项目根目录下会生成一个 users.xlsx 文件,可以在 Excel 或 Google Sheets 中打开。
读取现有的 Excel 文件
PhpSpreadsheet 可以轻松读取任何格式的数据。加载并输出内容的示例:
$inputFileName = 'users.xlsx';$spreadsheet = \\PhpOffice\\PhpSpreadsheet\\IOFactory::load($inputFileName);$sheet = $spreadsheet->getActiveSheet();
// 读取所有行$data = $sheet->toArray();
foreach ($data as $row) { echo implode(' | ', $row) . "";}toArray() 方法返回一个二维数组,其中第一个元素是索引为 0、1、2 的行。您也可以通过地址访问单元格:$sheet->getCell('A2')->getValue()。
样式与格式化操作
PhpSpreadsheet 的优势之一在于灵活控制表格的外观。
$styleArray = [ 'font' => [ 'bold' => true, 'size' => 12, 'color' => ['argb' => 'FF2E4057'], ], 'fill' => [ 'fillType' => \\PhpOffice\\PhpSpreadsheet\\Style\\Fill::FILL_SOLID, 'startColor' => ['argb' => 'FFD9E2EC'], ], 'borders' => [ 'allBorders' => [ 'borderStyle' => \\PhpOffice\\PhpSpreadsheet\\Style\\Border::BORDER_THIN, ], ],];
// 将样式应用到范围$sheet->getStyle('A1:C1')->applyFromArray($styleArray);
// 自动调整列宽foreach (range('A','C') as $col) { $sheet->getColumnDimension($col)->setAutoSize(true);}从数据库导出数据到 Excel
经常需要导出 SQL 查询结果。使用 PDO 的示例: