利用 PHP 直接輸出 HTTP 標頭與 Tab 分隔文字,瀏覽器即會提示下載 .xls 檔案。這是一種無需第三方函式庫、相容性極佳的輕量匯出方案。
<?php
// --- 資料庫連線設定 ---
$DB_Server = "localhost";
$DB_Username = "root";
$DB_Password = "123456";
$DB_DBName = "oa";
$DB_TBLName = "oa_form_table";
// --- 檔案命名 ---
$savename = date("YmdHis"); // 修正:原碼 "YmjHis" 格式錯誤
$file_type = "vnd.ms-excel";
$file_ending = "xls";
// --- 輸出 HTTP 標頭 ---
header("Content-Type: application/$file_type; charset=utf-8");
header("Content-Disposition: attachment; filename=$savename.$file_ending");
// header("Pragma: no-cache"); // 視需求啟用
// --- 連線資料庫 ---
$Connect = @mysqli_connect($DB_Server, $DB_Username, $DB_Password, $DB_DBName);
if (!$Connect) {
die("Couldn't connect: " . mysqli_connect_error());
}
mysqli_set_charset($Connect, "utf8");
// --- 查詢資料 ---
$sql = "SELECT * FROM `$DB_TBLName`";
$result = mysqli_query($Connect, $sql);
if (!$result) {
die("Query failed: " . mysqli_error($Connect));
}
// --- 輸出標題列 ---
$title = "資料庫:$DB_DBName, 資料表:$DB_TBLName, 匯出時間:" . date("Y-m-d H:i:s");
echo $title . "\n";
$sep = "\t";
$fieldCount = mysqli_num_fields($result);
for ($i = 0; $i < $fieldCount; $i++) {
$meta = mysqli_fetch_field_direct($result, $i);
echo $meta->name . $sep;
}
echo "\n";
// --- 輸出資料列 ---
while ($row = mysqli_fetch_row($result)) {
$schema_insert = "";
for ($j = 0; $j < $fieldCount; $j++) {
if (!isset($row[$j])) {
$schema_insert .= "NULL" . $sep;
} elseif ($row[$j] !== "") {
$schema_insert .= $row[$j] . $sep;
} else {
$schema_insert .= $sep;
}
}
// 移除結尾多餘分隔符並換行
$schema_insert = rtrim($schema_insert, $sep);
echo $schema_insert . "\n";
}
mysqli_free_result($result);
mysqli_close($Connect);
?>
| 項目 | 說明 |
|---|---|
| 標頭 Content-Type | application/vnd.ms-excel 讓瀏覽器識別為 Excel |
| Content-Disposition | attachment 強制下載,filename 指定檔名 |
| 字元編碼 | 標頭與資料庫連線皆設 utf-8,避免中文亂碼 |
| 分隔符 | 使用 \t (Tab),Excel 開啟時自動分欄 |
| 資料庫擴充 | 範例已更新為 mysqli (原碼使用已棄用的 mysql_*) |
| 欄位名稱 | 使用 mysqli_fetch_field_direct 取得原始欄位名 |
| NULL 處理 | 資料庫 NULL 值輸出為字串 "NULL" |
ob_flush()/flush() 逐段輸出,避免記憶體耗盡。echo "\xEF\xBB\xBF"; 可讓 Excel 直接以 UTF-8 開啟不需匯入嚮導。header() 前是否有輸出 (含空白、BOM),確保 mysqli_query 成功。