[{"data":1,"prerenderedAt":65},["ShallowReactive",2],{"article-107":3},{"code":4,"msg":5,"data":6,"count":14},200,"查询成功",{"id":7,"title":8,"keywords":9,"description":10,"category_id":11,"content":12,"body_html":13,"thumb_up":14,"clicks":15,"sort":14,"remark":13,"status":16,"is_open":16,"is_deleted":14,"is_top":16,"is_recommend":16,"create_time":17,"update_time":18,"image_id":19,"url":13,"member_id":14,"cate_name":20,"prev":21,"next":24,"tags":27,"words":36,"read_time":37,"comments":16,"cover":38,"relevant":39},107,"PHP 导出 Excel 的三种常用方法","php,excel,导出","本文详细讲解 PHP 导出 Excel 文件的三种方法：原生生成CSV适用于简单数据快速导出，需注意中文编码（添加 BOM 头；HTML 表格伪装 Excel快速生成基础表格，但兼容性差，不支持复杂样式；PhpSpreadsheet 库（推荐）支持复杂格式（合并单元格、公式、样式定制），可导出 .xlsx 或 .xls，并解决大数据量内存问题。  ",2,"以下是使用 PHP 导出 Excel 文件的详细步骤教程，涵盖原生 PHP 实现和常用第三方库两种方式，并提供完整代码示例。\n\n---\n### **方法 1：原生 PHP 生成 CSV（简单快速）**\n#### **适用场景**：数据量小，无需复杂格式。\n```php\n\u003C?php\n\u002F\u002F 1. 设置 HTTP 头，声明文件类型\nheader('Content-Type: text\u002Fcsv; charset=utf-8');\nheader('Content-Disposition: attachment; filename=\"data.csv\"');\n\n\u002F\u002F 2. 打开输出流（直接输出到浏览器）\n$output = fopen('php:\u002F\u002Foutput', 'w');\n\n\u002F\u002F 3. 添加 CSV 标题行\nfputcsv($output, ['ID', '姓名', '邮箱', '注册时间']);\n\n\u002F\u002F 4. 模拟数据（实际应从数据库获取）\n$data = [\n    [1, '张三', 'zhangsan@example.com', '2023-01-01'],\n    [2, '李四', 'lisi@example.com', '2023-02-15'],\n];\n\n\u002F\u002F 5. 写入数据行\nforeach ($data as $row) {\n    fputcsv($output, $row);\n}\n\n\u002F\u002F 6. 关闭流\nfclose($output);\nexit;\n?>\n```\n\n#### **注意事项**：\n1. CSV 本质是纯文本，不支持单元格样式或公式。\n2. 中文乱码问题：确保文件编码为 `UTF-8`，并添加 `BOM` 头（可选）：\n   ```php\n   echo \"\\xEF\\xBB\\xBF\"; \u002F\u002F 输出 BOM 头\n   ```\n\n---\n\n### **方法 2：使用 PHP 原生生成 HTML 表格（伪装为 Excel）**\n#### **适用场景**：快速生成简单表格，兼容性较差。\n```php\n\u003C?php\n\u002F\u002F 1. 设置 HTTP 头（伪装为 Excel 文件）\nheader('Content-Type: application\u002Fvnd.ms-excel');\nheader('Content-Disposition: attachment; filename=\"data.xls\"');\n\n\u002F\u002F 2. 输出 HTML 表格\necho '\u003Ctable border=\"1\">';\necho '\u003Ctr>\u003Cth>ID\u003C\u002Fth>\u003Cth>姓名\u003C\u002Fth>\u003Cth>邮箱\u003C\u002Fth>\u003C\u002Ftr>';\necho '\u003Ctr>\u003Ctd>1\u003C\u002Ftd>\u003Ctd>张三\u003C\u002Ftd>\u003Ctd>zhangsan@example.com\u003C\u002Ftd>\u003C\u002Ftr>';\necho '\u003Ctr>\u003Ctd>2\u003C\u002Ftd>\u003Ctd>李四\u003C\u002Ftd>\u003Ctd>lisi@example.com\u003C\u002Ftd>\u003C\u002Ftr>';\necho '\u003C\u002Ftable>';\nexit;\n?>\n```\n\n#### **缺点**：\n- 无法设置复杂样式。\n- 部分 Excel 版本可能提示格式错误。\n\n---\n\n### **方法 3：使用 PhpSpreadsheet 库（推荐，功能强大）**\n#### **适用场景**：需要生成复杂格式的 `.xlsx` 或 `.xls` 文件。\n\n#### **步骤 1：安装 PhpSpreadsheet**\n通过 Composer 安装：\n```bash\ncomposer require phpoffice\u002Fphpspreadsheet\n```\n\n#### **步骤 2：完整代码示例**\n```php\n\u003C?php\nrequire 'vendor\u002Fautoload.php';\nuse PhpOffice\\PhpSpreadsheet\\Spreadsheet;\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\n\n\u002F\u002F 1. 创建 Spreadsheet 对象\n$spreadsheet = new Spreadsheet();\n$sheet = $spreadsheet->getActiveSheet();\n\n\u002F\u002F 2. 设置标题行\n$sheet->setCellValue('A1', 'ID');\n$sheet->setCellValue('B1', '姓名');\n$sheet->setCellValue('C1', '邮箱');\n\n\u002F\u002F 3. 填充数据（模拟数据，实际应从数据库获取）\n$data = [\n    [1, '张三', 'zhangsan@example.com'],\n    [2, '李四', 'lisi@example.com'],\n];\n\n$row = 2; \u002F\u002F 从第二行开始\nforeach ($data as $item) {\n    $sheet->setCellValue('A' . $row, $item[0]);\n    $sheet->setCellValue('B' . $row, $item[1]);\n    $sheet->setCellValue('C' . $row, $item[2]);\n    $row++;\n}\n\n\u002F\u002F 4. 设置样式（可选）\n$sheet->getStyle('A1:C1')->applyFromArray([\n    'font' => [\n        'bold' => true,\n        'color' => ['rgb' => 'FFFFFF']\n    ],\n    'fill' => [\n        'fillType' => \\PhpOffice\\PhpSpreadsheet\\Style\\Fill::FILL_SOLID,\n        'startColor' => ['rgb' => '4CAF50']\n    ]\n]);\n\n\u002F\u002F 5. 自动调整列宽\nforeach (range('A', 'C') as $col) {\n    $sheet->getColumnDimension($col)->setAutoSize(true);\n}\n\n\u002F\u002F 6. 输出到浏览器\nheader('Content-Type: application\u002Fvnd.openxmlformats-officedocument.spreadsheetml.sheet');\nheader('Content-Disposition: attachment; filename=\"users.xlsx\"');\nheader('Cache-Control: max-age=0');\n\n$writer = new Xlsx($spreadsheet);\n$writer->save('php:\u002F\u002Foutput');\nexit;\n?>\n```\n\n#### **核心功能扩展**：\n1. **合并单元格**：\n   ```php\n   $sheet->mergeCells('A1:D1');\n   $sheet->setCellValue('A1', '用户列表');\n   ```\n2. **设置单元格格式**（日期、货币）：\n   ```php\n   $sheet->setCellValue('D2', '2023-10-01');\n   $sheet->getStyle('D2')->getNumberFormat()->setFormatCode('yyyy-mm-dd');\n   ```\n3. **添加公式**：\n   ```php\n   $sheet->setCellValue('E2', '=SUM(A2:A10)');\n   ```\n4. **导出为 PDF**：\n   ```php\n   use PhpOffice\\PhpSpreadsheet\\Writer\\Pdf\\Mpdf;\n   $writer = new Mpdf($spreadsheet);\n   $writer->save('php:\u002F\u002Foutput');\n   ```\n\n---\n\n## **常见问题解决**\n1. **中文乱码**：\n   - 确保文件编码为 `UTF-8`。\n   - 在输出前添加 BOM 头（仅限 CSV）：\n     ```php\n     echo \"\\xEF\\xBB\\xBF\";\n     ```\n\n2. **内存不足**（处理大数据量）：\n   - 分批次读取数据库数据。\n   - 使用 `Chunk` 处理：\n     ```php\n     $query->chunk(1000, function ($users) use ($sheet, &$row) {\n         foreach ($users as $user) {\n             $sheet->setCellValue('A' . $row, $user->id);\n             $row++;\n         }\n     });\n     ```\n\n3. **兼容性问题**：\n   - 导出为 `.xls` 格式（Excel 2003）：\n     ```php\n     $writer = new \\PhpOffice\\PhpSpreadsheet\\Writer\\Xls($spreadsheet);\n     ```\n\n---\n\n## **总结**\n- **简单数据快速导出**：使用 CSV 方法。\n- **复杂格式需求**：使用 PhpSpreadsheet 库。\n- **避免内存溢出**：分批次处理数据，及时释放内存。\n\n通过上述方法，可灵活实现 PHP 导出 Excel 的功能，满足不同场景需求。",null,0,222,1,"2025-03-29 04:24:59","2025-04-22 22:59:57",66,"PHP",{"id":22,"title":23},106,"阿里开源数据同步组件Canal",{"id":25,"title":26},108,"PHP中使用cURL实现Get和Post请求的方法",[28,31,34],{"id":29,"name":30},84,"导出",{"id":32,"name":33},85,"excel",{"id":35,"name":20},25,2352,5,"https:\u002F\u002Ftp.myong.top\u002Fstorage\u002Farticle\u002F20230407\u002Fe70ad72ca8f855e68e71fb0e124ede5a.jpeg",[40,45,50,55,60],{"id":41,"title":42,"create_time":43,"description":44},93,"PHP执行Python脚本解压，压缩文件夹操作","2020-08-06 14:59:05","PHP是有解压缩类文件的，但在实际项目中，用户方使用Python脚本压缩，很容易出现中文解压乱码，导致文件内容丢失的情况，本文主要介绍PHP执行Python脚本解压缩出现的问题以及解决方法",{"id":46,"title":47,"create_time":48,"description":49},92,"PHP对图片的处理","2020-07-30 15:53:38","图片处理函数功能：缩放、剪切、相框、水印、锐化、旋转、翻转、透明度、反色处理并保存历史记录的思路：当有图片有改动时自动生成一张新图片",{"id":51,"title":52,"create_time":53,"description":54},96,"PHP中字符串跟0做比较永远是true","2021-02-04 16:16:27","最近在项目中做数据对比的功能，发现一个特殊的情况，0跟任何字符串做比较永远返回true，特意了解了一下。",{"id":56,"title":57,"create_time":58,"description":59},13,"Win系统下配置PHP链接Oracle","2019-01-17 22:23:36","该文章内容主要介绍window系统下，php连接oracle的配置。",{"id":61,"title":62,"create_time":63,"description":64},103,"面向对象三大特性五大原则 + 低耦合高内聚[转载]","2021-10-31 23:18:58","面向对象的三大特性是\"封装、\"多态\"、\"继承\"，五大原则是\"单一职责原则\"、\"开放封闭原则\"、\"里氏替换原则\"、\"依赖倒置原则\"、\"接口分离原则\"。",1783431654616]