PHP如何生成统计报表

wen PHP项目 1

本文目录导读:

PHP如何生成统计报表

  1. 使用 HTML 表格生成简单报表
  2. 使用 Chart.js 生成可视化图表
  3. 使用 PhpSpreadsheet 生成 Excel 报表
  4. 生成 PDF 报表(使用 Dompdf)
  5. 使用 Google Charts API(无需本地库)
  6. 完整的报表生成类示例
  7. 推荐方案:

在PHP中生成统计报表有多种方法,我给您介绍几种常用的方案:

使用 HTML 表格生成简单报表

<?php
// 连接数据库
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 统计数据
$query = "SELECT 
    DATE(created_at) as date,
    COUNT(*) as total_orders,
    SUM(total_amount) as total_revenue
FROM orders 
WHERE created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
GROUP BY DATE(created_at)
ORDER BY date DESC";
$stmt = $pdo->query($query);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>销售报表</title>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
        tr:nth-child(even) { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h2>最近7天销售报表</h2>
    <table>
        <thead>
            <tr>
                <th>日期</th>
                <th>订单数</th>
                <th>总销售额</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $row): ?>
            <tr>
                <td><?php echo $row['date']; ?></td>
                <td><?php echo $row['total_orders']; ?></td>
                <td>¥<?php echo number_format($row['total_revenue'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>

使用 Chart.js 生成可视化图表

<?php
// 假设这是从数据库获取的数据
$months = ['1月', '2月', '3月', '4月', '5月', '6月'];
$sales = [12000, 15000, 18000, 16000, 20000, 24000];
$profits = [3000, 4500, 6000, 5200, 7800, 9200];
// 将PHP数组转换为JSON
$chart_data = json_encode([
    'labels' => $months,
    'sales' => $sales,
    'profits' => $profits
]);
?>
<!DOCTYPE html>
<html>
<head>销售趋势报表</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <canvas id="salesChart" width="800" height="400"></canvas>
    <script>
        // 从PHP传递数据到JavaScript
        const data = <?php echo $chart_data; ?>;
        const ctx = document.getElementById('salesChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.labels,
                datasets: [
                    {
                        label: '销售额',
                        data: data.sales,
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.1
                    },
                    {
                        label: '利润',
                        data: data.profits,
                        borderColor: 'rgb(255, 99, 132)',
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        tension: 0.1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '2024年销售趋势'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '¥' + value;
                            }
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>

使用 PhpSpreadsheet 生成 Excel 报表

首先安装依赖:

composer require phpoffice/phpspreadsheet
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
// 创建Spreadsheet对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', '月度销售统计报表');
$sheet->mergeCells('A1:D1');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);
$sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
// 设置表头
$sheet->setCellValue('A2', '月份');
$sheet->setCellValue('B2', '订单数');
$sheet->setCellValue('C2', '销售额');
$sheet->setCellValue('D2', '利润');
// 设置表头样式
$headerStyle = $sheet->getStyle('A2:D2');
$headerStyle->getFont()->setBold(true);
$headerStyle->getFill()
    ->setFillType(Fill::FILL_SOLID)
    ->getStartColor()->setARGB('4CAF50');
$headerStyle->getFont()->getColor()->setARGB('FFFFFF');
// 添加数据(示例数据)
$data = [
    ['2024-01', 120, 120000, 36000],
    ['2024-02', 150, 150000, 45000],
    ['2024-03', 180, 180000, 54000],
];
$row = 3;
foreach ($data as $item) {
    $sheet->setCellValue('A' . $row, $item[0]);
    $sheet->setCellValue('B' . $row, $item[1]);
    $sheet->setCellValue('C' . $row, $item[2]);
    $sheet->setCellValue('D' . $row, $item[3]);
    $row++;
}
// 设置列宽
$sheet->getColumnDimension('A')->setWidth(15);
$sheet->getColumnDimension('B')->setWidth(12);
$sheet->getColumnDimension('C')->setWidth(15);
$sheet->getColumnDimension('D')->setWidth(15);
// 添加边框
$sheet->getStyle('A2:D' . ($row - 1))->getBorders()
    ->getAllBorders()
    ->setBorderStyle(Border::BORDER_THIN);
// 生成文件并下载
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="销售报表.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
?>

生成 PDF 报表(使用 Dompdf)

<?php
require 'vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
// 生成HTML内容
$html = '
<html>
<head>
    <style>
        body { font-family: "Arial", sans-serif; }
        h2 { background-color: #4CAF50; color: white; padding: 10px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
    </style>
</head>
<body>
    <h2>销售统计报表</h2>
    <table>
        <tr>
            <th>月份</th>
            <th>订单数</th>
            <th>销售额</th>
        </tr>
        <tr>
            <td>2024-01</td>
            <td>120</td>
            <td>¥120,000</td>
        </tr>
        <tr>
            <td>2024-02</td>
            <td>150</td>
            <td>¥150,000</td>
        </tr>
        <tr>
            <td>2024-03</td>
            <td>180</td>
            <td>¥180,000</td>
        </tr>
    </table>
</body>
</html>';
// 初始化Dompdf
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
// 输出PDF
$dompdf->stream('统计报表.pdf', ['Attachment' => false]);
?>

使用 Google Charts API(无需本地库)

<?php
// 获取数据
$data = [
    ['任务', '完成数'],
    ['已完成', 75],
    ['进行中', 20],
    ['未开始', 5]
];
$jsonData = json_encode($data);
?>
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = google.visualization.arrayToDataTable(<?php echo $jsonData; ?>);
            var options = {
                title: '任务完成情况',
                is3D: true,
            };
            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>

完整的报表生成类示例

<?php
class ReportGenerator {
    private $pdo;
    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }
    // 生成销售日报
    public function generateDailySales($date) {
        $sql = "SELECT 
            product_name,
            SUM(quantity) as total_qty,
            SUM(price * quantity) as total_amount
        FROM sales 
        WHERE DATE(sale_date) = :date
        GROUP BY product_name";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':date' => $date]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    // 生成月度统计
    public function generateMonthlyStats($year, $month) {
        $sql = "SELECT 
            DAY(sale_date) as day,
            COUNT(*) as order_count,
            SUM(total_amount) as daily_total
        FROM orders 
        WHERE YEAR(sale_date) = :year 
        AND MONTH(sale_date) = :month
        GROUP BY DAY(sale_date)";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':year' => $year, ':month' => $month]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    // 导出CSV
    public function exportCSV($data, $filename = 'report.csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        $output = fopen('php://output', 'w');
        // 添加表头
        if (!empty($data)) {
            fputcsv($output, array_keys($data[0]));
        }
        // 添加数据行
        foreach ($data as $row) {
            fputcsv($output, $row);
        }
        fclose($output);
        exit();
    }
}
// 使用示例
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');
$report = new ReportGenerator($pdo);
// 生成某天的销售报表
$dailySales = $report->generateDailySales('2024-01-15');
$report->exportCSV($dailySales, 'sales_report.csv');
?>

推荐方案:

  1. 简单统计:使用 HTML 表格 + CSS
  2. 可视化图表:Chart.js 或 Google Charts
  3. Excel导出:PhpSpreadsheet
  4. PDF报告:Dompdf
  5. 大数据分析:考虑使用专门的报表工具如 AdminLTE + 后端聚合

选择哪种方式取决于您的具体需求:

  • 需要图表展示 → Chart.js
  • 需要Excel格式 → PhpSpreadsheet
  • 需要打印或PDF → Dompdf
  • 需要Web展示 → HTML表格或Chart.js

抱歉,评论功能暂时关闭!