Excel 文件內容編碼與 HTTP 響應頭聲明的編碼必須一致。現代瀏覽器均支持 UTF-8,建議統一使用 UTF-8,避免 GBK 轉換帶來的跨平台問題。
<?php
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
header("Content-Disposition: attachment; filename=export_data.xls");
?>
<!DOCTYPE html>
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="https://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table border="1">
<tr><th>編號</th><th>姓名</th></tr>
<tr><td>1</td><td>張三</td></tr>
</table>
</body>
</html>
優點:直接輸出 UTF-8 HTML,瀏覽器和 Excel 均能正確識別,無需 iconv 轉碼,跨平台兼容性最佳。
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
// 或強制 GBK
header("Content-Type: application/vnd.ms-excel; charset=GBK");
echo iconv('UTF-8', 'GBK', $cell_value); // 每個單元格需轉碼
缺點:需逐字段轉碼,易遺漏;Linux 服務器出 GBK 文件在 Windows Excel 打開正常,但 Mac/Linux LibreOffice 可能亂碼。
HTTP 標準 Content-Disposition 歷史不支持非 ASCII 文件名,各瀏覽器處理不同:
| 瀏覽器 | 推薦編碼方式 |
|---|---|
| Chrome / Firefox / Edge (新版) | RFC 5987 格式:filename*=UTF-8''%E6%96%87%E4%BB%B6%E5%90%8D.xls |
| IE / 舊版瀏覽器 | GBK/GB2312 URL 編碼:filename=%D6%D0%B9%FA.xls |
function set_download_filename($filename) {
$encoded = rawurlencode($filename); // UTF-8 URL 編碼
$ua = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/MSIE|Trident|Edge/', $ua)) {
// IE/Edge 老內核
header("Content-Disposition: attachment; filename=\"{$encoded}\"");
} else {
// 現代瀏覽器 RFC 5987
header("Content-Disposition: attachment; filename*=UTF-8''{$encoded}");
// 兼容舊版 Firefox
header("Content-Disposition: attachment; filename=\"{$filename}\"; filename*=UTF-8''{$encoded}");
}
}
composer require phpoffice/phpspreadsheet。charset=UTF-8。<meta charset="UTF-8">。iconv('UTF-8','GBK'),除非強制需求輸出 .xls 給舊版 Excel。