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

PHP 使用 PHPExcel 讀寫 Excel 檔案完整教學 (支援 .xls/.xlsx)

     編輯:PHP 相關知識

注意:PHPExcel 專案已於 2017 年停止維護,官方建議遷移至 PhpSpreadsheet。本文保留 PHPExcel 教學供維護舊專案參考,新專案請直接使用 PhpSpreadsheet (API 高度相容)。

環境準備

  1. 下載 PHPExcel 1.8+ (最後版本)。
  2. 解壓後核心檔案:PHPExcel.php 與 PHPExcel/ 目錄。
  3. 需啟用 PHP 擴充:php_zip, php_xml, php_gd2 (圖片處理), php_mbstring。

讀取 Excel (.xls / .xlsx)

<?php
require_once 'PHPExcel.php';

// 自動偵測格式並載入
$file = 'data.xlsx'; // 或 data.xls
$reader = PHPExcel_IOFactory::createReaderForFile($file);
$spreadsheet = $reader->load($file);

// 取得第一個工作表
$sheet = $spreadsheet->getSheet(0);

// 取得最大列 (字母) 與最大行 (數字)
$highestColumn = $sheet->getHighestColumn(); // 如 'G'
$highestRow = $sheet->getHighestRow();       // 如 100

// 將欄位字母轉數字索引 (A=0, B=1...)
$colCount = PHPExcel_Cell::columnIndexFromString($highestColumn);

$data = [];
for ($row = 1; $row <= $highestRow; $row++) {
    $rowData = [];
    for ($col = 0; $col < $colCount; $col++) {
        $cell = $sheet->getCellByColumnAndRow($col, $row);
        $value = $cell->getValue();
        // 處理日期/公式等特殊型別
        if ($cell->getDataType() === PHPExcel_Cell_DataType::TYPE_NUMERIC) {
            if (PHPExcel_Shared_Date::isDateTime($cell)) {
                $value = PHPExcel_Shared_Date::convertToObject($cell->getCalculatedValue())->format('Y-m-d');
            }
        }
        $rowData[] = $value;
    }
    $data[] = $rowData;
}

// $data 現在是二維陣列,可直接存入資料庫或處理
print_r($data);
?>

寫入 Excel (.xls 格式相容性最佳)

<?php
require_once 'PHPExcel.php';

$spreadsheet = new PHPExcel();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('用戶資料');

// 設定標題列
$headers = ['ID', '姓名', 'Email', '建立日期'];
$sheet->fromArray($headers, null, 'A1');

// 樣式:標題列加粗、背景色
$style = [
    'font' => ['bold' => true],
    'fill' => [
        'fillType' => PHPExcel_Style_Fill::FILL_SOLID,
        'startColor' => ['rgb' => '4472C4'],
        'endColor' => ['rgb' => '4472C4'],
    ],
    'font' => ['color' => ['rgb' => 'FFFFFF'], 'bold' => true],
];
$sheet->getStyle('A1:D1')->applyFromArray($style);

// 填入資料 (假設從資料庫查出)
$users = [
    [1, '張三', 'zhang@example.com', '2023-01-15'],
    [2, '李四', 'li@example.com', '2023-02-20'],
];
$sheet->fromArray($users, null, 'A2');

// 自動欄寬
foreach (range('A', 'D') as $col) {
    $sheet->getColumnDimension($col)->setAutoSize(true);
}

// 輸出為 .xls (Excel 97-2003 相容性最好)
$writer = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel5');
$filename = 'users_' . date('Ymd_His') . '.xls';

// 直接下載
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
?>

寫入 .xlsx (Office Open XML)

<?php
// ... 建立 $spreadsheet 同前 ...
$writer = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="users_' . date('Ymd_His') . '.xlsx"');
$writer->save('php://output');
exit;
?>

常見問題與技巧

問題解決方案
記憶體不足大檔案使用 setReadDataOnly(true) 僅讀資料;或改用 PhpSpreadsheet 的 ChunkReadFilter 分塊讀取;調大 memory_limit。
日期讀出成數字 (如 44927)Excel 日期儲存為序數,需用 PHPExcel_Shared_Date::isDateTime() 判斷並 convertToObject() 轉換。
公式不計算讀取時需 $reader->setLoadSheetsOnly() 或手動呼叫 $cell->getCalculatedValue()。
中文亂碼確保 PHP 檔案存為 UTF-8,資料庫連線 SET NAMES utf8mb4,Excel 儲存格字型支援中文 (預設 Calibri 即可)。
數字前導零消失 (如 001 變 1)寫入前將欄位格式設為文字:$sheet->getStyle('A2:A100')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

遷移至 PhpSpreadsheet 快速指南

  • 安裝:composer require phpoffice/phpspreadsheet
  • 命名空間:PHPExcel → PhpOffice\PhpSpreadsheet\Spreadsheet,PHPExcel_IOFactory → PhpOffice\PhpSpreadsheet\IOFactory。
  • 類名稱前綴 PHPExcel_ 移除,如 PHPExcel_Cell → PhpOffice\PhpSpreadsheet\Cell\Cell。
  • 大部分 API 參數順序、方法名稱保持一致,修改 use 陳述式即可運行。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved