首页 > 解决方案 > PHPOfficePhpSpreadsheet 找不到空单元格(没有值或 0)

问题描述

我在使用 PhpSpreadsheet 时遇到了一些奇怪的问题。我正在处理一个 excel 文件,其中的列数和位置因发件人而异。因此,我首先将文件中的特定单元格内容与数据库进行匹配。当找到匹配项时,我得到列位置(编号),即哪一列中的哪些数据用于该特定文件。除了检查空单元格或值等于 0,00 的单元格之外,我的脚本中的所有内容都运行良好。

我的脚本中的检查(或部分检查):

$spreadSheet = $Reader->load($targetPath);
$excelSheet = $spreadSheet->getActiveSheet();
$spreadSheetAry = $excelSheet->toArray();
$sheetCount = count($spreadSheetAry);

$client_city = $settings->client_city_column - 1;
$client_name = $settings->client_name_column - 1;
//where $settings->client_name_column is actually the column number
//I subtract 1, because the scripts starts count from 0, but for the user it is more friendly to count from 1 when settings the things up

for ($i = $data_start_row; $i < $sheetCount; $i++) {
    if (empty($spreadSheetAry[$i][$client_name])) {
        $ImportCommandeDistributorLine->description = $langs->trans(
        'ErrorEmptyFieldForValue',
        $langs->trans('Customer'),
        $i + 1
        );
        $ImportCommandeDistributorLine->create($user);
        $error++;
    }
    if (empty($spreadSheetAry[$i][$client_city])) {
        $ImportCommandeDistributorLine->description = $langs->trans(
        'ErrorEmptyFieldForValue',
        $langs->trans('City'),
        $i + 1
        );
        $ImportCommandeDistributorLine->create($user);
        $error++;
    }
    //and so on for all columns. Some have numbers, some have text as cell content
}

我也试过:

for ($i = $data_start_row; $i < $sheetCount; $i++) {
    if ($spreadSheetAry[$i][$client_name] === null || 
       $spreadSheetAry[$i][$client_name] === '') {
          $ImportCommandeDistributorLine->description = $langs->trans(
          'ErrorEmptyFieldForValue',
          $langs->trans('Customer'),
          $i + 1
          );
          $ImportCommandeDistributorLine->create($user);
          $error++;
    }
}

'$ImportCommandeDistributorLine' 在 LOG 中插入一行用于此文件处理,'$error++' 稍后使用,这意味着如果有错误,脚本将在此停止。然后,我可以打开日志卡并查看错误。在继续之前,我需要检查大约 10 个不同的列。不幸的是,以上 2 次尝试均无效。

另一方面,如果单元格具有0,00值,则在数据库中将其插入为NULL,所以对我来说,即使是第一个选项也必须有效。不知道为什么不。

标签: phpphpspreadsheetphpoffice-phpspreadsheet

解决方案


推荐阅读