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

PHPExcel 讀寫 Excel 實戰筆記:從資料匯入到樣式化匯出完整範例

     編輯:PHP 綜合知識

前言

PHPExcel(現已併入 PhpSpreadsheet,建議新專案直接使用 PhpSpreadsheet)是 PHP 操作 Excel 最經典的庫。本文整理讀取、寫入、樣式設定、匯出下載的實戰碼,供快速參考。


一、讀取 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>';
?>

關鍵點:

  • 支援 `.xls` (BIFF)、`.xlsx` (OOXML)、`.csv`、`.ods` 等格式
  • `getCellByColumnAndRow($col, $row)` 索引從 1 開始
  • 大檔案建議啟用 ReadFilter 分塊讀取,避免記憶體耗盡

二、建立並匯出 Excel(含樣式、合併儲存格、欄寬)

<?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()` 迴圈。
  • 記憶體優化:`$spreadsheet->disconnectWorksheets()` 釋放記憶體;或使用 CellIterator 搭配 ReadFilter 流式讀取。
  • 快取:`$spreadsheet->setPreCalculateFormulas(false)` 關閉公式預計算;匯出大檔案可啟用 cache_to_disk。

五、遷移提醒:PHPExcel → PhpSpreadsheet

PHPExcel 於 2017 年停止維護,**PhpSpreadsheet** 為其繼任者,命名空間從 `PHPExcel_*` 改為 `PhpOffice\PhpSpreadsheet\*`,功能更強、支援 PHP 7.1+、效能更好。Composer 安裝:

composer require phpoffice/phpspreadsheet

結語

本文提供 PHPExcel/PhpSpreadsheet 讀寫 Excel 的完整實戰範例,涵蓋資料讀取、樣式化匯出、公式、合併儲存格、下載輸出等常見需求。掌握核心 API 後,可靈活應用於報表匯出、資料匯入驗證、樣板填充等企業級場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved