PHPExcel(現已併入 PhpSpreadsheet,建議新專案直接使用 PhpSpreadsheet)是 PHP 操作 Excel 最經典的庫。本文整理讀取、寫入、樣式設定、匯出下載的實戰碼,供快速參考。
<?php
require_once 'vendor/autoload.php'; // Composer 安裝 PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
$file = 'D:/datas.xlsx';
if (!file_exists($file)) {
die("檔案不存在:$file");
}
$spreadsheet = IOFactory::load($file);
$sheets = $spreadsheet->getAllSheets();
$sheetData = [];
foreach ($sheets as $sheetIndex => $sheet) {
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$colCount = Coordinate::columnIndexFromString($highestCol);
for ($row = 1; $row <= $highestRow; $row++) {
for ($col = 1; $col <= $colCount; $col++) {
$cellValue = $sheet->getCellByColumnAndRow($col, $row)->getValue();
$sheetData[$sheetIndex][$col][$row] = $cellValue;
}
}
}
echo '<pre>';
print_r($sheetData);
echo '</pre>';
?>
關鍵點:
ReadFilter 分塊讀取,避免記憶體耗盡<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
// 建立試算表
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('出貨重量統計');
// === 標題列 ===
$sheet->setCellValue('A1', '訂單編號: ORD-20240115');
$sheet->setCellValue('B1', '材積重 (kg)');
$sheet->setCellValue('D1', '實際重 (kg)');
// 合併儲存格
$sheet->mergeCells('B1:C1');
$sheet->mergeCells('D1:E1');
// 欄寬
$sheet->getColumnDimension('A')->setWidth(12);
$sheet->getColumnDimension('B')->setWidth(18);
$sheet->getColumnDimension('C')->setWidth(18);
$sheet->getColumnDimension('D')->setWidth(18);
$sheet->getColumnDimension('E')->setWidth(18);
// === 表頭列 ===
$headers = ['箱號', '商品', '出貨箱', '系統重', '實際重'];
$col = 'A';
foreach ($headers as $h) {
$sheet->setCellValue($col . '2', $h);
$col++;
}
// 樣式:表頭置中、粗體、底色
$headerRange = 'A2:E2';
$sheet->getStyle($headerRange)->getFont()->setBold(true);
$sheet->getStyle($headerRange)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle($headerRange)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF96B7F6');
// === 資料列(模擬資料庫查詢結果)===
$data = [
['BOX 001', 12.50, 13.20, 12.80, 13.00],
['BOX 002', 8.30, 8.50, 8.40, 8.45],
['BOX 003', 15.00, 14.80, 15.10, 15.05],
];
$row = 3;
foreach ($data as $record) {
$col = 'A';
foreach ($record as $val) {
$sheet->setCellValue($col . $row, $val);
$col++;
}
// 數值欄靠右對齊
$sheet->getStyle("B$row:E$row")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
// 千分位格式
$sheet->getStyle("B$row:E$row")->getNumberFormat()->setFormatCode('#,##0.00');
$row++;
}
// === 總計列 ===
$sheet->setCellValue("A$row", '總計');
$sheet->setCellValue("B$row", '=SUM(B3:B' . ($row-1) . ')');
$sheet->setCellValue("D$row", '=SUM(D3:D' . ($row-1) . ')');
$sheet->getStyle("A$row:E$row")->getFont()->setBold(true);
$sheet->getStyle("A$row:E$row")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF96B7F6');
// === 匯出下載 ===
$filename = 'weight-' . date('YmdHis') . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
?>
| 需求 | 程式碼片段 |
|---|---|
| 字型、大小、粗體 | $style->getFont()->setName('微軟正黑體')->setSize(12)->setBold(true); |
| 水平置中/靠右/靠左 | $style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); |
| 垂直置中 | $style->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); |
| 背景色 (ARGB) | $style->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF0000'); |
| 邊框 | $style->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN); |
| 數字格式(金額、日期、百分比) | $style->getNumberFormat()->setFormatCode('#,##0.00'); |
| 合併儲存格 | $sheet->mergeCells('A1:C1'); |
| 凍結窗格 | $sheet->freezePane('A3'); |
| 自動換行 | $style->getAlignment()->setWrapText(true); |
fromArray() 批次寫入,避免逐儲存格 `setCellValue()` 迴圈。CellIterator 搭配 ReadFilter 流式讀取。cache_to_disk。PHPExcel 於 2017 年停止維護,**PhpSpreadsheet** 為其繼任者,命名空間從 `PHPExcel_*` 改為 `PhpOffice\PhpSpreadsheet\*`,功能更強、支援 PHP 7.1+、效能更好。Composer 安裝:
composer require phpoffice/phpspreadsheet
本文提供 PHPExcel/PhpSpreadsheet 讀寫 Excel 的完整實戰範例,涵蓋資料讀取、樣式化匯出、公式、合併儲存格、下載輸出等常見需求。掌握核心 API 後,可靈活應用於報表匯出、資料匯入驗證、樣板填充等企業級場景。