萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 生成 Excel 檔案至指定目錄:PHPExcel 實作與避坑指南

常見誤區:header('Content-Disposition: attachment') 只能觸發瀏覽器下載,**無法直接存檔到伺服器目錄**。若需伺服器端生成檔案,須使用 PHPExcel(或 PhpSpreadsheet)程式庫寫入檔案系統。

核心概念區別

方式輸出目標適用場景
HTTP Header 下載瀏覽器下載資料夾使用者主動匯出報表
PHPExcel 寫入檔案伺服器指定路徑定時任務、後台自動生成、附件存檔

PHPExcel 完整匯出範例

<?php
require_once 'vendor/autoload.php'; // Composer 安裝 phpoffice/phpexcel

use PHPExcel;
use PHPExcel_Writer_Excel2007;
use PHPExcel_IOFactory;

function exportExcel($data, $title = [], $filename = 'export', $fields = []) {
    if (!$data || !is_array($data)) return false;
    
    // 可選:只匯出指定欄位且保持順序
    if ($fields) {
        $newData = [];
        foreach ($data as $row) {
            $newRow = [];
            foreach ($fields as $f) $newRow[$f] = $row[$f] ?? '';
            $newData[] = $newRow;
        }
        $data = $newData;
    }
    
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("System")->setTitle($filename);
    
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setTitle('Sheet1');
    
    // 寫入標題列
    if ($title) {
        $col = 'A';
        foreach ($title as $t) {
            $sheet->setCellValue($col . '1', $t);
            $col++;
        }
        $startRow = 2;
    } else {
        $startRow = 1;
    }
    
    // 寫入資料
    foreach ($data as $rowIdx => $row) {
        $col = 'A';
        foreach ($row as $val) {
            $sheet->setCellValue($col . ($startRow + $rowIdx), $val);
            $col++;
        }
    }
    
    // 自動欄寬
    foreach ($sheet->getColumnIterator() as $col) {
        $sheet->getColumnDimension($col->getColumnIndex())->setAutoSize(true);
    }
    
    // 存檔 .xlsx (Excel 2007+)
    $writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $savePath = __DIR__ . "/exports/{$filename}_" . date('Ymd_His') . ".xlsx";
    $writer->save($savePath);
    
    return $savePath;
}

// 使用範例
$data = [
    ['id'=>1, 'name'=>'張三', 'email'=>'zhang@example.com'],
    ['id'=>2, 'name'=>'李四', 'email'=>'li@example.com'],
];
exportExcel($data, ['ID','姓名','Email'], 'users', ['id','name','email']);
// 生成檔案:exports/users_20240115_143022.xlsx

插入圖片

$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Company Logo');
$objDrawing->setPath(__DIR__ . '/logo.png'); // 本地圖片路徑
$objDrawing->setCoordinates('A1');
$objDrawing->setOffsetX(10);
$objDrawing->setWidth(120);
$objDrawing->setWorksheet($sheet);

遷移建議:PhpSpreadsheet(PHPExcel 繼任者)

composer require phpoffice/phpspreadsheet

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
// ... 操作 API 大同小異
$writer = new Xlsx($spreadsheet);
$writer->save($path);
  • PHPExcel 已停止維護(2017),PhpSpreadsheet 為官方繼承專案
  • 命名空間、型別提示、效能、記憶體管理全面改善
  • 支援 .xlsx、.xls、.ods、.csv、.html、.pdf 多格式

大資料量效能優化

  • 使用 setCellValueExplicit 指定資料型別,減少自動推斷開銷
  • 分批寫入、定期 flush() 釋放記憶體
  • 考慮 CSV 格式:fputcsv 速度快 10 倍以上,記憶體極低
  • 超大報表改用 Spout(串流寫入,恆定記憶體)

伺服器端生成 Excel 檔案,核心在於「程式庫寫入檔案系統」而非「HTTP 下載標頭」,選對工具與格式事半功倍。

copyright © 萬盛學電腦網 all rights reserved