首先,連接到MySQL 數據庫並進行查詢。假設數據庫中已有一個名為users的表格,包含id 、 name和email等字段。
<?php
// 數據庫連接設置
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 查詢數據
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
?>
接下來,我們使用PHP 將查詢結果導出為CSV 文件。 mysqli_result對像中的數據將逐行提取並寫入到CSV 文件。
<?php
// 如果查詢結果存在
if ($result->num_rows > 0) {
// 設置文件名
$filename = "users_data_" . date("Ymd_His") . ".csv";
// 設置響應頭,告訴瀏覽器下載文件
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
// 打開輸出流
$output = fopen('php://output', 'w');
// 寫入表頭
$header = ['ID', 'Name', 'Email'];
fputcsv($output, $header);
// 寫入數據行
while ($row = $result->fetch_assoc()) {
fputcsv($output, $row);
}
// 關閉輸出流
fclose($output);
}
?>
雖然直接生成Excel 文件稍微複雜,但可以通過第三方庫PHPExcel或PhpSpreadsheet來實現。這兩個庫提供了豐富的功能,能夠將查詢結果導出為.xls或.xlsx格式的文件。
下面是一個基本的導出Excel 的例子,首先需要安裝PhpSpreadsheet :
composer require phpoffice/phpspreadsheet
然後在PHP 中使用如下代碼導出數據:
<?php
// 引入 PhpSpreadsheet 類庫
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// 創建新的電子表格對象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 設置表頭
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Name');
$sheet->setCellValue('C1', 'Email');
// 填充數據
$rowNum = 2;
while ($row = $result->fetch_assoc()) {
$sheet->setCellValue('A' . $rowNum, $row['id']);
$sheet->setCellValue('B' . $rowNum, $row['name']);
$sheet->setCellValue('C' . $rowNum, $row['email']);
$rowNum++;
}
// 設置文件名
$filename = "users_data_" . date("Ymd_His") . ".xlsx";
// 設置響應頭,告訴瀏覽器下載文件
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// 創建 Writer 對象
$writer = new Xlsx($spreadsheet);
// 輸出文件
$writer->save('php://output');
?>
如果您希望將數據表格呈現給用戶以供打印,可以將查詢結果以HTML 表格的形式輸出。用戶可以直接使用瀏覽器的打印功能進行打印。
<?php
// 如果查詢結果存在
if ($result->num_rows > 0) {
echo '<table border="1">';
echo '<thead>';
echo '<tr><th>ID</th><th>Name</th><th>Email</th></tr>';
echo '</thead>';
echo '<tbody>';
// 輸出數據行
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
// 添加打印按鈕
echo '<br><button onclick="window.print()">打印表格</button>';
}
?>
這樣,用戶可以點擊打印按鈕,將頁面內容以表格形式打印出來。