通过phpspreadsheet从Excel文件导入数据,并检查数据库symfony 4中记录的存在

问题描述

我将通过phpspreadsheet从Excel文件导入数据,并逐行读取并测试记录是否存在于数据库中,如下所示

list

检查记录是否存在于数据库中仅适用于一半的记录,如下所示:

$reader = new XlsxReader();
$spreadsheet = $reader->load($tmp_name);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn();
fwrite($fp,"File: " . $_FILES['catalogue']['name'] . "\n");
fwrite($fp,"Number of Row : " . $highestRow . "\n");
fwrite($fp,"Highest Column : " . $highestColumn . "\n");
$em = $this->getDoctrine()->getManager()->getRepository(Catalogue::class);
$list = [];

$it = $worksheet->getRowIterator(1);
foreach ($it as $row) {
    $cellIt = $row->getCellIterator();
    $r = [];
    foreach ($cellIt as $cell) {
        $r[] = $cell->getFormattedValue();
    }
    $list[] = $r;
}
foreach ($list as $x) {
    $v = $x[0];
    fwrite($fp,$v . "\n");
    $s = $em->findOneBy(['Species' => $x[0]]);
    if ($s) {
        if ($s->getSpecies() ==$x[0]){
        $request->getSession()->getFlashBag()->add('error',$v . 'Already Existing' . '<br>');
        fwrite($fp,$x[0].'Already Exist in the catalogue'. "\n");
        }
        if ($s->getSpecies() !=$x[0]) {
        $request->getSession()->getFlashBag()->add('sucess',$x[0] . 'To be added' . '<br>');
       fwrite($fp,$x[0]. 'to be added to the catalogue'. "\n");
        }

    }

    //
}
fclose($fp);
$request->getSession()->getFlashBag()->add('success','File is valid,and was successfully processed.!' . '<br>' . "<a href=" . $url . ">Log Link</a>");
return $this->redirect($this->generateUrl('Catalogue_list'));

只有前三个记录在数据库中。我在做什么错了?

解决方法

仅当物种已经存在于数据库中时,对findOneBy方法的调用才会返回某些内容,而您不需要嵌套的if。您应该只将第二个(具有!=条件的那个)移动到else块,因为现在永远无法达到它:

$s = $em->findOneBy(['Species' => $x[0]]);
if ($s) {  // $s is set,so the species exists
    $request->getSession()->getFlashBag()->add('error',$v . 'Already Existing' . '<br>');
    fwrite($fp,$x[0].'Already Exist in the catalogue'. "\n");
} else {  // Not found
    $request->getSession()->getFlashBag()->add('sucess',$x[0] . 'To be added' . '<br>');
   fwrite($fp,$x[0]. 'to be added to the catalogue'. "\n");
}
,
object MyApp1 {
  def main(args: Array[String]) = {
    log4j.setName("File" -> "MyApp1.log")
    println("HelloWorld")
  }
}
object MyApp2 {
  def main(args: Array[String]) = {
    log4j.setName("File" -> "MyApp2.log")
    println("HelloWorld")
  }
}
I got this error Argument 1 passed to App\Entity\Catalogue::setSpecies() must be of the type string,null given,Any help

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...