本文目录导读:

- 基础数据准备(数据库查询)
- 生成 HTML 格式对账单(适合网页预览)
- 导出 PDF 对账单(推荐方式)
- 生成 Excel 对账单(适合财务人员)
- 核心处理逻辑封装(企业级应用)
- 常用注意事项
- 简单 API 接口示例
在 PHP 中生成对账单通常涉及数据汇总、格式化输出和导出文件三个核心环节,下面提供几种常见的实现方式,从简单到复杂:
基础数据准备(数据库查询)
你需要从数据库汇总账单数据:
<?php
// 1. 获取对账日期范围
$startDate = '2024-01-01';
$endDate = '2024-01-31';
$customerId = 123;
// 2. 查询账单数据
$sql = "SELECT
o.order_no,
o.order_date,
o.total_amount,
o.payment_status,
p.payment_method
FROM orders o
LEFT JOIN payments p ON o.order_id = p.order_id
WHERE o.customer_id = ?
AND o.order_date BETWEEN ? AND ?
ORDER BY o.order_date ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$customerId, $startDate, $endDate]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
生成 HTML 格式对账单(适合网页预览)
<!DOCTYPE html>
<html>
<head>客户对账单</title>
<style>
.statement { width: 80%; margin: 0 auto; font-family: Arial, sans-serif; }
.header { background: #f0f0f0; padding: 20px; text-align: center; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
th { background: #4CAF50; color: white; }
.total-row { font-weight: bold; background: #f9f9f9; }
</style>
</head>
<body>
<div class="statement">
<div class="header">
<h2>客户对账单</h2>
<p>客户名称:<?= htmlspecialchars($customerName) ?></p>
<p>账单周期:<?= $startDate ?> 至 <?= $endDate ?></p>
</div>
<table>
<tr>
<th>订单号</th>
<th>日期</th>
<th>金额</th>
<th>支付方式</th>
<th>状态</th>
</tr>
<?php foreach ($orders as $order): ?>
<tr>
<td><?= $order['order_no'] ?></td>
<td><?= $order['order_date'] ?></td>
<td>¥ <?= number_format($order['total_amount'], 2) ?></td>
<td><?= $order['payment_method'] ?></td>
<td><?= $order['payment_status'] ?></td>
</tr>
<?php endforeach; ?>
<!-- 汇总行 -->
<tr class="total-row">
<td colspan="2">合计</td>
<td>¥ <?= number_format($totalAmount, 2) ?></td>
<td>订单数</td>
<td><?= count($orders) ?></td>
</tr>
</table>
</div>
</body>
</html>
导出 PDF 对账单(推荐方式)
使用 TCPDF 或 FPDF 库:
<?php
// 需要安装:composer require tecnickcom/tcpdf
require_once 'vendor/autoload.php';
// 创建 PDF 实例
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator('Your Company');
$pdf->SetTitle('客户对账单');
// 添加页面
$pdf->AddPage();
// 设置字体
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, '客户对账单', 0, 1, 'C');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 6, '客户名称:' . $customerName, 0, 1);
$pdf->Cell(0, 6, '账单周期:' . $startDate . ' 至 ' . $endDate, 0, 1);
$pdf->Ln(10);
// 表格头
$pdf->SetFillColor(220, 220, 220);
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(60, 8, '订单号', 1, 0, 'C', 1);
$pdf->Cell(40, 8, '日期', 1, 0, 'C', 1);
$pdf->Cell(40, 8, '金额', 1, 0, 'C', 1);
$pdf->Cell(50, 8, '备注', 1, 1, 'C', 1);
// 数据行
$pdf->SetFont('helvetica', '', 10);
foreach ($orders as $order) {
$pdf->Cell(60, 8, $order['order_no'], 1);
$pdf->Cell(40, 8, $order['order_date'], 1);
$pdf->Cell(40, 8, '¥ ' . number_format($order['total_amount'], 2), 1);
$pdf->Cell(50, 8, $order['payment_status'], 1, 1);
}
// 合计行
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(100, 10, '合计', 1);
$pdf->Cell(40, 10, '¥ ' . number_format($totalAmount, 2), 1, 1);
// 输出 PDF
$pdf->Output('cust_statement_' . date('Ymd') . '.pdf', 'D'); // D 为下载
?>
生成 Excel 对账单(适合财务人员)
使用 PhpSpreadsheet 库:
<?php
// 需要安装:composer require phpoffice/phpspreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// 创建电子表格
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
行
$sheet->setCellValue('A1', '订单号');
$sheet->setCellValue('B1', '订单日期');
$sheet->setCellValue('C1', '金额');
$sheet->setCellValue('D1', '状态');
// 设置表头样式
$sheet->getStyle('A1:D1')->getFont()->setBold(true);
$sheet->getStyle('A1:D1')->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB('FFC0C0C0');
// 填充数据
$row = 2;
foreach ($orders as $order) {
$sheet->setCellValue('A'.$row, $order['order_no']);
$sheet->setCellValue('B'.$row, $order['order_date']);
$sheet->setCellValue('C'.$row, $order['total_amount']);
$sheet->setCellValue('D'.$row, $order['payment_status']);
$row++;
}
// 合计行
$sheet->setCellValue('B'.$row, '合计');
$sheet->setCellValue('C'.$row, "=SUM(C2:C".($row-1).")");
$sheet->getStyle("A{$row}:D{$row}")->getFont()->setBold(true);
// 调整列宽
foreach(range('A','D') as $columnID) {
$sheet->getColumnDimension($columnID)->setAutoSize(true);
}
// 保存文件
$writer = new Xlsx($spreadsheet);
$writer->save('对账单_' . date('Ymd') . '.xlsx');
?>
核心处理逻辑封装(企业级应用)
<?php
class StatementService
{
/**
* 生成对账单数据
*/
public function generateStatementData($customerId, $startDate, $endDate)
{
// 1. 获取客户信息
$customer = $this->getCustomerInfo($customerId);
// 2. 获取交易记录
$transactions = $this->getTransactions($customerId, $startDate, $endDate);
// 3. 计算汇总
$summary = [
'total_amount' => array_sum(array_column($transactions, 'amount')),
'total_count' => count($transactions),
'paid_amount' => 0,
'unpaid_amount' => 0
];
foreach ($transactions as $transaction) {
if ($transaction['status'] == 'paid') {
$summary['paid_amount'] += $transaction['amount'];
} else {
$summary['unpaid_amount'] += $transaction['amount'];
}
}
return [
'customer' => $customer,
'transactions' => $transactions,
'summary' => $summary,
'period' => "{$startDate} 至 {$endDate}"
];
}
/**
* 导出多种格式
*/
public function export($format = 'pdf', $data)
{
switch ($format) {
case 'pdf':
return $this->exportPDF($data);
case 'excel':
return $this->exportExcel($data);
case 'csv':
return $this->exportCSV($data);
default:
throw new Exception("不支持的导出格式");
}
}
/**
* 发送邮件
*/
public function sendEmail($email, $data, $format = 'pdf')
{
$file = $this->export($format, $data);
$mailer = new \PHPMailer\PHPMailer\PHPMailer();
$mailer->isSMTP();
$mailer->Host = 'smtp.yourcompany.com';
$mailer->addAddress($email);
$mailer->Subject = '你的对账单';
$mailer->Body = "您好,您的对账单已生成,请查收附件。";
$mailer->addStringAttachment($file, '对账单.pdf');
return $mailer->send();
}
}
?>
常用注意事项
| 注意事项 | 说明 |
|---|---|
| 时区问题 | 统一使用 date_default_timezone_set() 设置时区 |
| 金额精度 | 使用 DECIMAL(10,2) 存储,计算时用 bcmath 扩展 |
| 加密传输 | 对账数据敏感,建议使用 HTTPS |
| 权限控制 | 非管理员只能查看自己的账单 |
| 审计日志 | 记录谁在什么时间查看了哪些对账单 |
简单 API 接口示例
<?php
// api/generate_statement.php
header('Content-Type: application/json');
$params = json_decode(file_get_contents('php://input'), true);
$customerId = $params['customer_id'] ?? 0;
$startDate = $params['start_date'] ?? date('Y-m-01');
$endDate = $params['end_date'] ?? date('Y-m-t');
$format = $params['format'] ?? 'json'; // json, pdf, excel
try {
$service = new StatementService();
$data = $service->generateStatementData($customerId, $startDate, $endDate);
if ($format == 'json') {
echo json_encode($data);
} else {
$service->export($format, $data);
}
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
}
?>
根据你的实际需求选择方案:
- 网页预览 → 直接 HTML + 样式
- PDF 下载 → TCPDF/FPDI(推荐)
- Excel 分析 → PhpSpreadsheet
- 邮件推送 → 结合 PHPMailer
- 实时接口 → 封装为 RESTful API
建议将核心逻辑(数据汇总、计算)与展示层分离,便于后期维护和扩展。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播