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

如何用PHP导入XLS文件时过滤空行?

解决PHP导入XLS文件时过滤空行的问题

你的代码未对空行做判断,导致所有行(包括空行)都被处理。可以通过检查行内字段是否为空来过滤空行,具体修改如下:

修改后的完整代码

require('xls/php-excel-reader/excel_reader2.php');
require('xls/SpreadsheetReader.php');
require_once '_inc/_db.php';

$r = rand();
$mimes = ['application/vnd.ms-excel', 'text/xls', 'text/xlsx', 'application/vnd.oasis.opendocument.spreadsheet'];

if (in_array($_FILES["file"]["type"], $mimes)) {
    $uploadFilePath = 'storage/' . basename($_FILES['file']['name']);
    
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
    rename($uploadFilePath, "storage/" . $r . ".xls");
    
    $uploadFilePath = "storage/" . $r . ".xls";
    $Reader = new SpreadsheetReader($uploadFilePath);

    $totalSheet = count($Reader->sheets());

    $tot = 0;
    /* 遍历所有工作表 */
    for ($i = 0; $i < $totalSheet; $i++) {
        $Reader->ChangeSheet($i);
        $tots = $totalSheet;
        foreach ($Reader as $Row) {
            // 过滤空行:检查该行所有单元格去除空白后是否全为空
            $isBlankRow = true;
            foreach ($Row as $cell) {
                if (trim((string)$cell) !== '') {
                    $isBlankRow = false;
                    break;
                }
            }
            if ($isBlankRow) {
                continue; // 跳过空行
            }

            $tot++;
            $nrcontenitore = isset($Row[0]) ? $Row[0] : '';
            $nrcontenitore = str_replace(".", "", $nrcontenitore);
            $nrcontenitore = str_replace("-", "", $nrcontenitore);
            $nrcontenitore = str_replace("_", "", $nrcontenitore);
            $nrcontenitore = str_replace("/", "", $nrcontenitore);
            $nrcontenitore = str_replace("'", "", $nrcontenitore);
            $nrcontenitore = preg_replace('/\s+/', '', $nrcontenitore);

            // 注意:你这里重复赋值了$nrcontenitore,建议删除下面这行
            // $nrcontenitore = isset($Row[0]) ? $Row[0] : '';
            $data = isset($Row[1]) ? $Row[1] : '';

            $doc .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "\n";
            $docarr .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "#\n";
        }
    }
}

关键修改点

  • 新增空行判断逻辑:遍历当前行所有单元格,只要有一个单元格去除空白后不为空,就判定为非空行;否则直接跳过该行。
  • 修复代码冗余:你在清洗完$nrcontenitore后又重新赋值原始的$Row[0],这会覆盖之前的清洗操作,建议删除该行重复代码。

简化判断(可选)

如果业务只需要关注特定列(比如第0列和第1列)是否为空,可以简化判断逻辑,提升效率:

// 仅判断关键列是否为空
$nrcontenitore = isset($Row[0]) ? trim((string)$Row[0]) : '';
$data = isset($Row[1]) ? trim((string)$Row[1]) : '';
if (empty($nrcontenitore) && empty($data)) {
    continue;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:40:57