瀏覽器/Excel 支援直接開啟 <table> 結構的 .xls 檔案。利用輸出緩衝捕獲 HTML,再寫入檔案,無需第三方庫 (如 PHPExcel/PhpSpreadsheet) 即可快速實作簡單匯出。
<?php
class ExcelExporter {
public function start() {
ob_start(); // 開啟輸出緩衝
}
public function save($path) {
$data = ob_get_contents();
ob_end_clean();
$this->writeFile($path, $data);
}
private function writeFile($path, $data) {
$dir = dirname($path);
if (!is_dir($dir)) mkdir($dir, 0755, true);
$fp = fopen($path, 'wb');
fwrite($fp, $data);
fclose($fp);
}
}
?>
<?php
require 'ExcelExporter.php';
require 'db_config.php'; // 包含 $pdo
$excel = new ExcelExporter();
$excel->start();
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<table border="1">
<thead>
<tr>
<th>公司中文名</th>
<th>公司英文名</th>
<th>聯絡人</th>
<th>職位</th>
<th>電話</th>
<th>傳真</th>
<th>Email</th>
<th>網站</th>
<th>產品</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $pdo->query("SELECT * FROM map ORDER BY register_date DESC");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
foreach (['companyname_cn','companyname_en','name','position','tel','fax','email','website','product'] as $col) {
echo "<td>" . htmlspecialchars($row[$col] ?? '') . "</td>";
}
echo "</tr>";
}
?>
</tbody>
</table>
<?php
$excel->save("Excel/data_" . date('Ymd') . ".xls");
echo "匯出完成:Excel/data_" . date('Ymd') . ".xls";
?>
$excel->start():啟用 ob_start() 捕獲後續所有輸出 (HTML)。<meta charset=utf-8> 確保中文不亂碼。htmlspecialchars() 防止 HTML 注入破壞結構。$excel->save():取得緩衝內容,寫入 .xls 檔案。| 優點 | 缺點 |
|---|---|
| 零依賴、程式碼極簡 | 僅支援基本表格,無法設定欄寬、樣式、公式 |
| 記憶體效率高 (緩衝流式) | 大數據量 (超過 5 萬列) 易導致 Excel 開啟緩慢或記憶體不足 |
| 相容性好 (Excel、LibreOffice、Google Sheets 皆可開) | 無法處理合併儲存格、多工作表、圖表等進階功能 |
fputcsv() 逐行寫入,無格式但通用性最高。SELECT ... INTO OUTFILE (MySQL) 或 COPY TO (PostgreSQL) 效能最佳。<?php
$filename = 'export_' . date('Ymd_His') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');
$excel->start();
?>
<meta charset="utf-8">
<table>...</table>
<?php
$excel->save('php://output'); // 直接輸出到瀏覽器
?>