PHPExcel(現已併入 PhpSpreadsheet)是 PHP 導出 Excel 的經典庫。本文示範基本導出流程、樣式設定、中文編碼處理。
<?php
require_once './Classes/PHPExcel.php';
$data = [
['id'=>1001, 'username'=>'張飛', 'password'=>'123456', 'address'=>'三國時高老莊250巷101室'],
['id'=>1002, 'username'=>'關羽', 'password'=>'123456', 'address'=>'三國時花果山'],
['id'=>1003, 'username'=>'曹操', 'password'=>'123456', 'address'=>'延安西路2055弄3號'],
['id'=>1004, 'username'=>'劉備', 'password'=>'654321', 'address'=>'愚園路188號3309室'],
];
$objPHPExcel = new PHPExcel();
// 設定文件屬性
$objPHPExcel->getProperties()
->setCreator('MyApp')
->setTitle('用戶資料匯出')
->setSubject('用戶資料')
->setDescription('使用 PHPExcel 導出')
->setKeywords('excel php export')
->setCategory('報表');
// 設定標題列
$sheet = $objPHPExcel->setActiveSheetIndex(0);
$sheet->setCellValue('A1', 'ID')
->setCellValue('B1', '用戶名')
->setCellValue('C1', '密碼')
->setCellValue('D1', '地址');
// 填入資料
$row = 2;
foreach ($data as $item) {
$sheet->setCellValue('A'.$row, $item['id'])
->setCellValue('B'.$row, $item['username'])
->setCellValue('C'.$row, $item['password'])
->setCellValue('D'.$row, $item['address']);
$row++;
}
$sheet->setTitle('用戶清單');
$objPHPExcel->setActiveSheetIndex(0);
// 輸出為 Excel 2007 (.xlsx)
$filename = urlencode('用戶資料統計表') . '_' . date('YmdHis');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
header('Cache-Control: max-age=0');
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$writer->save('php://output');
exit;
若輸出中文亂碼,需將字串轉為 GB2312/Big5:
$str = mb_convert_encoding($str, 'GB2312', 'UTF-8');
// 或使用 iconv
$str = iconv('UTF-8', 'GB2312//IGNORE', $str);
建議:現代專案改用 PhpSpreadsheet(PHPExcel 繼任者),原生支援 UTF-8,無需編碼轉換。
$objPHPExcel->setCacheStorageMethod('PHPCache')setActiveSheetIndex()