要将PHP数据库输出到Excel,你可以使用PHPExcel库,以下是一个简单的示例:
1、确保你已经安装了PHPExcel库,如果没有,可以通过Composer安装:

(图片来源网络,侵删)
composer require phpoffice/phpexcel
2、创建一个PHP文件(export_to_excel.php),并编写以下代码:
<?php
// 引入PHPExcel库
require_once 'vendor/autoload.php';
// 创建一个新的PHPExcel对象
$objPHPExcel = new PHPExcel();
// 设置文档属性
$objPHPExcel->getProperties()->setCreator("Your Name")
->setLastModifiedBy("Your Name")
->setTitle("Database Export to Excel")
->setSubject("Database Export to Excel")
->setDescription("Exporting database data to Excel using PHPExcel.")
->setKeywords("database export excel phpexcel")
->setCategory("Database");
// 连接到数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 查询数据库数据
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
// 将数据写入Excel表格
if ($result->num_rows > 0) {
// 设置表头
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Column1')
->setCellValue('B1', 'Column2')
->setCellValue('C1', 'Column3');
// 填充数据
$rowCount = 2;
while($row = $result->fetch_assoc()) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A' . $rowCount, $row['column1'])
->setCellValue('B' . $rowCount, $row['column2'])
->setCellValue('C' . $rowCount, $row['column3']);
$rowCount++;
}
} else {
echo "No results found";
}
// 设置活动工作表标题
$objPHPExcel->getActiveSheet()->setTitle('Database Data');
// 设置活动工作表索引为第一个工作表,以便Excel打开时显示的是第一个工作表
$objPHPExcel->setActiveSheetIndex(0);
// 设置HTTP头部信息,以便浏览器下载文件而不是在浏览器中打开它
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="database_data.xls"');
header('Cache-Control: max-age=0');
// 保存并输出Excel文件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?> 3、替换代码中的数据库连接信息、表名和列名,然后运行此PHP文件,这将生成一个名为database_data.xls的Excel文件,其中包含从数据库表中导出的数据。
小伙伴们,上文介绍php 数据库输出excel_PHP的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。

(图片来源网络,侵删)
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/68511.html