首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 匯出 Excel 兩大開源庫:php-excel (簡易) 與 PHPExcel (功能完整)

     編輯:PHP 綜合知識

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. 替代方案對比

建議選型

  1. 需完整 Excel 功能(樣式、公式、多工作表) → PhpSpreadsheet。
  2. 大量資料匯出、記憶體敏感 → Box/Spout 或原生 fputcsv。
  3. Laravel 專案 → FastExcel / Laravel-Excel (MaartenKoopman/Excel)。
  4. 單純 CSV 匯出 → 直接 fputcsv,零依賴、最高效能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
庫狀態格式支援記憶體效率學習曲線
PhpSpreadsheet積極維護XLSX, XLS, CSV, ODS, HTML, PDF中 (可分塊)中
Box/Spout維護中XLSX, CSV, ODS極佳 (串流)低
FastExcel (Laravel)維護中XLSX, CSV良好低 (Collection 介面)
fputcsv 原生內建CSV極佳極低