欢迎来到全国社交动力网络科技有限公司
建站资讯

当前位置: 首页 > 建站资讯 > 建站教程 > PHP教程

PHP代码怎么实现数据导出Excel_PHPExcel库与CSV导出方法

作者:app建站 来源:php培训学校哪家好日期:2025-10-19
推荐使用PhpSpreadsheet或CSV导出Excel,前者支持复杂样式,后者轻量高效;根据数据量和需求选择:小数据用PhpSpreadsheet,大数据用CSV。

php代码怎么实现数据导出excel_phpexcel库与csv导出方法

PHP中实现数据导出为Excel文件,常用的方法有两种:使用PHPExcel库(或其后续项目PhpSpreadsheet)生成真正的Excel文件,以及通过CSV格式导出,简单高效。下面分别介绍这两种方式的实现方法。

使用PhpSpreadsheet库导出Excel

注意:PHPExcel已停止维护,推荐使用其继任者 PhpSpreadsheet,支持.xlsx格式。

1. 通过Composer安装PhpSpreadsheet:

composer require phpoffice/phpspreadsheet

2. 示例代码:将数组数据导出为Excel文件

立即学习“PHP免费学习笔记(深入)”;

use PhpOffice\PhpSpreadsheet\Spreadsheet;use PhpOffice\PhpSpreadsheet\Writer\xlsx;$spreadsheet = new Spreadsheet();$sheet = $spreadsheet->getActiveSheet();// 设置表头$sheet->setCellValue('A1', '姓名');$sheet->setCellValue('B1', '年龄');$sheet->setCellValue('C1', '邮箱');// 假设这是从数据库获取的数据$data = [    ['张三', 28, 'zhangsan@example.com'],    ['李四', 30, 'lisi@example.com'],    ['王五', 25, 'wangwu@example.com']];$rowIndex = 2; // 数据从第2行开始foreach ($data as $row) {    $sheet->setCellValue('A' . $rowIndex, $row[0]);    $sheet->setCellValue('B' . $rowIndex, $row[1]);    $sheet->setCellValue('C' . $rowIndex, $row[2]);    $rowIndex++;}// 设置输出头,触发浏览器下载header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');header('Content-Disposition: attachment;filename="export.xlsx"');header('Cache-Control: max-age=0');$writer = new Xlsx($spreadsheet);$writer->save('php://output');
登录后复制

使用CSV格式导出数据

CSV导出无需第三方库,适合大数据量导出,兼容Excel打开。

阿里云-虚拟数字人 阿里云-虚拟数字人

阿里云-虚拟数字人是什么? ...

阿里云-虚拟数字人2 查看详情 阿里云-虚拟数字人

1. 示例代码:将数据导出为CSV文件

// 要导出的数据$data = [    ['姓名', '年龄', '邮箱'],    ['张三', 28, 'zhangsan@example.com'],    ['李四', 30, 'lisi@example.com'],    ['王五', 25, 'wangwu@example.com']];// 设置输出头header('Content-Type: text/csv; charset=utf-8');header('Content-Disposition: attachment; filename="export.csv"');// 打开输出流$output = fopen('php://output', 'w');// 设置UTF-8 BOM,避免中文乱码(特别是Excel打开时)fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));// 写入数据foreach ($data as $row) {    fputcsv($output, $row);}// 关闭输出流fclose($output);
登录后复制

提示:CSV方式更轻量,但不支持复杂样式;PhpSpreadsheet功能强大,可设置单元格样式、合并单元格等,但占用内存较高。

根据实际需求选择合适的方式。小数据量且需要格式化推荐PhpSpreadsheet;大数据导出优先考虑CSV。

基本上就这些。

以上就是PHP代码怎么实现数据导出Excel_PHPExcel库与CSV导出方法的详细内容,更多请关注php中文网其它相关文章!

标签: php培训视频
上一篇: PHP框架怎么实现数据加密_PHP框架数据加密算法与安全存储方案
下一篇: 暂无

推荐建站资讯

更多>