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

如何在使用PhpOffice\PhpSpreadsheet插入数据时忽略表头行

如何在PhpSpreadsheet导入数据时忽略表头行?

要忽略Excel文件的第一行表头,你可以通过以下几种简单方法实现,结合你的现有代码给出具体修改方案:

方法一:移除数组首个元素

将工作表数据转为数组后,直接用array_shift()移除第一行(表头行),再循环插入数据库:

修改后的关键代码片段:

$spreadSheet = $Reader->load($targetPath);
$sheetData = $spreadSheet->getActiveSheet()->toArray();

// 移除第一行表头
array_shift($sheetData);

// Loop through the rows from xlsx file for insert
foreach($sheetData as $row) {
    $regno = isset($row[0]) ? $row[0] : "";
    $fullname = isset($row[1]) ? $row[1] : "";
    $course = isset($row[2]) ? $row[2] : "";
    $status = 1;
    $pin = strtoupper(substr(md5(mt_rand()), 0, 10));

    // Insert into db
    $fieUploaded = $conn->itStudentsFileUpload($regno,$fullname,$course,$pin,$current_session,$status);
    if ($fieUploaded) {
        echo "Success";
    }
}

方法二:循环时跳过索引为0的行

在foreach循环中增加索引判断,直接跳过第一行(索引0对应表头行):

修改后的循环部分代码:

// Loop through the rows from xlsx file for insert
foreach($sheetData as $index => $row) {
    // 跳过第一行表头
    if ($index === 0) {
        continue;
    }

    $regno = isset($row[0]) ? $row[0] : "";
    $fullname = isset($row[1]) ? $row[1] : "";
    $course = isset($row[2]) ? $row[2] : "";
    $status = 1;
    $pin = strtoupper(substr(md5(mt_rand()), 0, 10));

    // Insert into db
    $fieUploaded = $conn->itStudentsFileUpload($regno,$fullname,$course,$pin,$current_session,$status);
    if ($fieUploaded) {
        echo "Success";
    }
}

方法三:使用PhpSpreadsheet读取过滤器

通过设置读取过滤器,让Reader从第2行开始读取数据(Excel行号从1开始计数),直接跳过表头行:

修改后的Reader初始化部分代码:

// 定义读取过滤器
class SkipFirstRowFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
    public function readCell($column, $row, $worksheetName = '') {
        // 只读取第2行及以后的行
        return $row >= 2;
    }
}

$Reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$Reader->setReadDataOnly(true);
// 设置读取过滤器
$Reader->setReadFilter(new SkipFirstRowFilter());
$spreadSheet = $Reader->load($targetPath);
$sheetData = $spreadSheet->getActiveSheet()->toArray();

// 后续循环逻辑保持不变
foreach($sheetData as $row) {
    // 你的插入代码
}

以上三种方法都能实现忽略表头行的需求,前两种方法更简洁,适配你的现有代码结构。

内容的提问来源于stack exchange,提问作者Bashir Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:55:15