1. php-excel (Google Code 專案,已封存)
- 極簡單純產生 Excel (BIFF/CSV)。
- 專案頁:
https://code.google.com/p/php-excel/ (已遷移至 GitHub/封存)。
- 適合:快速匯出簡單表格、無格式需求。
2. PHPExcel (CodePlex,現已遷移至 GitBox/PhpSpreadsheet)
- 功能完整:讀寫 Excel 2007 (OOXML)、Excel 5/95、CSV、HTML、PDF、ODS。
- 支援樣式、公式、圖表、圖片、資料驗證、條件格式。
- 專案頁:
https://github.com/PHPOffice/PHPExcel (標記 Deprecated)。
- 繼任者:PhpSpreadsheet — 重構、命名空間、PSR 相容、效能更好、積極維護。
3. PhpSpreadsheet 現代用法範例
composer require phpoffice/phpspreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World')
->setCellValue('A2', 123)
->setCellValue('B2', '=A2*2');
$writer = new Xlsx($spreadsheet);
$writer->save('hello.xlsx');
4. 讀取 Excel 範例
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = IOFactory::load('data.xlsx');
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
echo $cell->getCoordinate() . ' => ' . $cell->getValue() . "\n";
}
}
5. 大資料量匯出優化
- 使用
ChunkReadFilter 分塊讀取,避免記憶體爆炸。
- 匯出時關閉不需要的功能:
$writer->setPreCalculateFormulas(false)。
- 考慮 CSV 格式:
Csv writer 速度最快、記憶體最低。
- 極大檔案改用串流寫入:
fopen('php://output', 'w') + fputcsv。
6. 替代方案對比
| 庫 | 狀態 | 格式支援 | 記憶體效率 | 學習曲線 |
| PhpSpreadsheet | 積極維護 | XLSX, XLS, CSV, ODS, HTML, PDF | 中 (可分塊) | 中 |
| Box/Spout | 維護中 | XLSX, CSV, ODS | 極佳 (串流) | 低 |
| FastExcel (Laravel) | 維護中 | XLSX, CSV | 良好 | 低 (Collection 介面) |
| fputcsv 原生 | 內建 | CSV | 極佳 | 極低 |
建議選型
- 需完整 Excel 功能(樣式、公式、多工作表) → PhpSpreadsheet。
- 大量資料匯出、記憶體敏感 → Box/Spout 或原生
fputcsv。
- Laravel 專案 → FastExcel / Laravel-Excel (MaartenKoopman/Excel)。
- 單純 CSV 匯出 → 直接
fputcsv,零依賴、最高效能。
- 上一篇文章: PHP Memcached 應用實作:安裝、啟動、php-memcached-client 完整教學
- 下一篇文章: PHP 處理百萬級資料庫查詢優化 30 條鐵律:索引、SQL 寫法、架構層面
Copyright ©
程式碼之家 All Rights Reserved