php导出数据为excel表格
作者:野牛程序员:2024-02-02 21:28:17php阅读 2642
使用PHP导出数据为Excel表格可以通过使用PHPExcel库(现在已经不再活跃)或者更现代的库,比如PhpSpreadsheet来实现。以下是使用PhpSpreadsheet库的示例代码:
<?php // 引入Composer自动加载器 require 'vendor/autoload.php'; use PhpOffice\\PhpSpreadsheet\\Spreadsheet; use PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx; // 创建新的Excel对象 $spreadsheet = new Spreadsheet(); // 设置Excel表格的属性 $spreadsheet->getProperties() ->setCreator('Your Name') ->setLastModifiedBy('Your Name') ->setTitle('Sample Excel Export') ->setSubject('Sample Excel Export') ->setDescription('Sample Excel file for data export') ->setKeywords('excel php spreadsheet') ->setCategory('Test file'); // 添加数据到工作表 $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'ID'); $sheet->setCellValue('B1', 'Name'); $sheet->setCellValue('C1', 'Email'); // 模拟数据 $data = array( array(1, 'John Doe', 'john@example.com'), array(2, 'Jane Smith', 'jane@example.com'), array(3, 'Tom Brown', 'tom@example.com') ); // 逐行添加数据 $row = 2; foreach ($data as $item) { $col = 'A'; foreach ($item as $cell) { $sheet->setCellValue($col . $row, $cell); $col++; } $row++; } // 设置HTTP头信息 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="sample.xlsx"'); header('Cache-Control: max-age=0'); // 创建Excel Writer对象 $writer = new Xlsx($spreadsheet); // 保存Excel文件到php://output $writer->save('php://output');
在这个例子中,首先创建了一个新的Excel对象,设置了一些基本的属性,然后添加了数据到工作表中,并最终将Excel文件以流的形式输出到浏览器,用户可以直接下载。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:查看windows进程端口
- 下一篇:php使用curl发起https请求