在開發 Web 應用程式時,我們經常需要提供 Excel 匯出功能。一般來說,我們可以使用 CSV、XLS、XLSX 等格式來產生 Excel 檔案。如果你不想安裝 Laravel-Excel 或其他外部套件,可以考慮使用 Excel 2003 兼容的 XML 格式,這樣可以直接在 Excel 開啟檔案,而不會遇到格式錯誤。
在這篇文章中,我們將介紹 如何使用 PHP 產生 Excel 2003 XML 格式 (.xls) 的檔案,並提供 簡單的 Laravel Controller 來處理 Excel 下載。
如何在 Laravel 中匯出 .xls?
我們將實作一個 簡單的 Laravel Controller,用來產生 Excel 2003 XML 格式,並讓使用者下載。
建立 Laravel Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class ExportController extends Controller
{
public function exportXML()
{
$fileName = "users.xls";
$headers = [
"Content-Type" => "application/vnd.ms-excel",
"Content-Disposition" => "attachment; filename=$fileName",
];
$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<?mso-application progid="Excel.Sheet"?>';
$xml .= '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">';
$xml .= '<Worksheet ss:Name="Users">';
$xml .= '<Table>';
// 產生標題列
$xml .= '<Row>';
$headersList = ['姓名', '年齡', '職業'];
foreach ($headersList as $header) {
$xml .= '<Cell><Data ss:Type="String">' . htmlspecialchars($header) . '</Data></Cell>';
}
$xml .= '</Row>';
// 產生範例資料
$data = [
['小明', 25, '工程師'],
['小華', 30, '設計師'],
['阿國', 28, '老師']
];
foreach ($data as $row) {
$xml .= '<Row>';
foreach ($row as $cell) {
$type = is_numeric($cell) ? 'Number' : 'String';
$xml .= '<Cell><Data ss:Type="' . $type . '">' . htmlspecialchars($cell) . '</Data></Cell>';
}
$xml .= '</Row>';
}
$xml .= '</Table></Worksheet></Workbook>';
return response($xml, 200, $headers);
}
}
設定 Laravel 路由
在 routes/web.php
中,新增下載 .xls
檔案的 API:
use App\Http\Controllers\ExportController; Route::get('/export-xml', [ExportController::class, 'exportXML']);
這樣,當使用者造訪 你的網域/export-xml
,就會自動下載 users.xls
檔案。
結論
-
這種方法使用 Excel 2003 XML 格式,無需安裝額外的 Laravel 套件。
-
產生的
.xls
檔案可以直接在 Excel 打開,不會遇到格式錯誤。 -
適合 簡單的資料輸出,但無法支援進階格式 (如合併儲存格、顏色等)。
-
如果需要 更強大的 Excel 功能,建議使用 Laravel-Excel (maatwebsite/excel)。