用php写个导出excel
时间: 2023-11-27 12:52:45 浏览: 68
php导出excel
5星 · 资源好评率100%
表格的代码该怎么写?
你可以使用以下代码来导出Excel表格:
```php
<?php
//连接数据库
$user = 'username';
$password = 'password';
$db = 'database_name';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db, $port);
//查询数据
$query = "SELECT * FROM table_name";
$result = mysqli_query($link, $query);
//创建Excel文件
require_once 'PHPExcel/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
//添加表头
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Column1');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Column2');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Column3');
//添加数据
$i = 2;
while ($row = mysqli_fetch_array($result)) {
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $i, $row['column1']);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $i, $row['column2']);
$objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $row['column3']);
$i++;
}
//保存Excel文件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('filename.xlsx');
?>
```
请注意,需要安装PHPExcel库才能运行此代码。
阅读全文