# PHP中怎么將數據導出成Excel表格
## 前言
在Web開發中,數據導出為Excel表格是一個常見的需求。無論是報表生成、數據備份還是信息共享,Excel格式因其通用性和易用性而廣受歡迎。PHP作為流行的服務器端腳本語言,提供了多種方式實現這一功能。本文將詳細介紹5種主流方法,并分析其優缺點。
## 方法一:使用原生PHP輸出CSV格式
### 實現原理
CSV(Comma-Separated Values)是一種簡單的表格數據格式,Excel可以直接打開。
```php
<?php
// 設置HTTP頭信息
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// 打開輸出流
$output = fopen('php://output', 'w');
// 寫入表頭
fputcsv($output, ['ID', '姓名', '年齡', '郵箱']);
// 模擬數據
$data = [
[1, '張三', 25, 'zhangsan@example.com'],
[2, '李四', 30, 'lisi@example.com']
];
// 寫入數據行
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
exit;
PHPExcel曾是PHP處理Excel的標桿庫,雖已停止更新但仍被廣泛使用。
composer require phpoffice/phpexcel
<?php
require 'vendor/autoload.php';
// 創建Excel對象
$objPHPExcel = new PHPExcel();
// 設置當前活動表
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
// 設置表頭
$sheet->setCellValue('A1', 'ID')
->setCellValue('B1', '姓名')
->setCellValue('C1', '年齡');
// 填充數據
$data = [
[1, '王五', 28],
[2, '趙六', 35]
];
$row = 2;
foreach ($data as $item) {
$sheet->setCellValue('A'.$row, $item[0])
->setCellValue('B'.$row, $item[1])
->setCellValue('C'.$row, $item[2]);
$row++;
}
// 輸出Excel文件
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="data.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
PhpSpreadsheet是PHPExcel的官方繼承者,支持PHP7+。
composer require phpoffice/phpspreadsheet
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// 創建電子表格對象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 設置樣式
$sheet->getStyle('A1:C1')->getFont()->setBold(true);
// 合并單元格示例
$sheet->mergeCells('A1:C1');
$sheet->setCellValue('A1', '員工信息表');
// 填充數據
$sheet->fromArray(
[
['ID', '姓名', '部門'],
[1001, '張三', '技術部'],
[1002, '李四', '市場部']
],
null,
'A2'
);
// 自動調整列寬
foreach(range('A','C') as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// 生成文件
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="employees.xlsx"');
$writer->save('php://output');
// 添加多個工作表
$spreadsheet->createSheet();
$spreadsheet->setActiveSheetIndex(1);
$sheet2 = $spreadsheet->getActiveSheet();
$sheet2->setTitle('銷售數據');
// 條件格式
$conditional = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$conditional->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS)
->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN)
->addCondition(0);
$conditional->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
$sheet->getStyle('B2:B10')->setConditionalStyles([$conditional]);
通過輸出HTML表格并設置MIME類型,可被Excel識別。
<?php
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=report.xls");
echo '<table border="1">
<tr>
<th>日期</th>
<th>銷售額</th>
<th>增長率</th>
</tr>
<tr>
<td>2023-01-01</td>
<td>¥15,000</td>
<td>12%</td>
</tr>
</table>';
exit;
<?php
$data = [
'api_key' => 'YOUR_API_KEY',
'data' => [
['產品', '銷量', '庫存'],
['手機', 150, 80],
['筆記本', 90, 120]
],
'options' => [
'file_name' => 'product_report',
'format' => 'xlsx'
]
];
$ch = curl_init('https://api.export-to-excel.com/v1/generate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
file_put_contents('report.xlsx', $response);
// 使用分塊處理
$chunkSize = 1000;
foreach (array_chunk($largeData, $chunkSize) as $chunk) {
$sheet->fromArray($chunk, null, 'A'.$row);
$row += $chunkSize;
}
// 使用緩存
$cacheMethod = \PhpOffice\PhpSpreadsheet\Settings::setCache(
new \PhpOffice\PhpSpreadsheet\Cache\Filesystem()
);
ob_start('ob_gzhandler');
// ...導出代碼...
ob_end_flush();
// CSV文件添加BOM頭
echo "\xEF\xBB\xBF";
set_time_limit(0);
ini_set('memory_limit', '512M');
// 舊版Excel兼容
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
本文詳細介紹了PHP導出Excel的5種主流方法,從簡單的CSV導出到功能全面的PhpSpreadsheet庫。對于大多數應用場景,推薦使用PhpSpreadsheet方案,它在功能性和維護性之間取得了良好平衡。實際開發中應根據項目需求、數據規模和功能要求選擇最合適的方案。
注意:示例代碼可能需要根據實際環境調整,特別是路徑和依賴管理部分。建議在生產環境使用前進行充分測試。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。