You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP将HTML表格与作为数据库的Excel电子表格关联?

PHP 对接 Excel 实现出勤表格系统的最优方案

现在主流的实现方式是使用 PhpSpreadsheet(它是已废弃的PHPExcel的官方继任者,持续维护且支持PHP 7.4+及更高版本),相比5年前的方案,它性能更优、API更简洁,还支持最新的Excel格式(.xlsx/.xlsm等)。

核心步骤实现

1. 安装依赖

用Composer快速安装PhpSpreadsheet:

composer require phpoffice/phpspreadsheet

2. 读取Excel中的出勤数据(模拟数据库查询)

比如读取包含姓名、出勤状态、日期、上下班时间的工作表,筛选指定日期的记录:

<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

// 加载Excel文件
$spreadsheet = IOFactory::load('./attendance.xlsx');
$worksheet = $spreadsheet->getActiveSheet();

// 遍历行(跳过表头,从第2行开始)
$attendanceRecords = [];
foreach ($worksheet->getRowIterator(2) as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false); // 读取空单元格
    
    $record = [
        'name' => $cellIterator->current()->getValue(),
        'status' => $cellIterator->next()->getValue(),
        'date' => $cellIterator->next()->getValue(),
        'check_in' => $cellIterator->next()->getValue(),
        'check_out' => $cellIterator->next()->getValue()
    ];
    $attendanceRecords[] = $record;
}

// 筛选2024-05-20的记录
$targetDate = '2024-05-20';
$filteredRecords = array_filter($attendanceRecords, function($item) use ($targetDate) {
    return $item['date'] === $targetDate;
});

3. 写入出勤数据到Excel(模拟数据库插入/更新)

比如新增一条出勤记录,或更新已有记录:

<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

// 加载现有文件或创建新文件
try {
    $spreadsheet = IOFactory::load('./attendance.xlsx');
} catch (\Exception $e) {
    // 文件不存在则创建新表格
    $spreadsheet = new Spreadsheet();
    $worksheet = $spreadsheet->getActiveSheet();
    // 写入表头
    $worksheet->setCellValue('A1', '姓名')
              ->setCellValue('B1', '出勤状态')
              ->setCellValue('C1', '日期')
              ->setCellValue('D1', '上班时间')
              ->setCellValue('E1', '下班时间');
}

$worksheet = $spreadsheet->getActiveSheet();
// 获取最后一行,追加新记录
$lastRow = $worksheet->getHighestRow() + 1;

// 写入新数据
$worksheet->setCellValue('A' . $lastRow, '张三')
          ->setCellValue('B' . $lastRow, '正常')
          ->setCellValue('C' . $lastRow, date('Y-m-d'))
          ->setCellValue('D' . $lastRow, date('H:i:s'))
          ->setCellValue('E' . $lastRow, '');

// 保存文件(覆盖原文件)
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('./attendance.xlsx');

优化建议

  • 避免频繁读写文件:如果有大量操作,先将数据加载到内存处理,最后一次性写入Excel,减少磁盘IO开销。
  • 使用缓存:PhpSpreadsheet支持内存缓存(比如Redis、APC),处理大文件时能显著提升性能。
  • 限制操作范围:只加载需要的工作表,避免遍历整个文件;读取时指定单元格范围(如$worksheet->rangeToArray('A2:E100'))。
  • 数据验证:写入前校验数据格式(比如日期格式、时间格式),避免Excel出现无效数据。

注意事项

Excel本质是文件而非数据库,不适合高并发、大数据量的场景。如果你的系统后期用户量或数据量增长,建议迁移到MySQL、SQLite等关系型数据库,再通过PhpSpreadsheet实现Excel导入导出的功能。

内容的提问来源于stack exchange,提问作者Justin Allen Azucena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:32:20