使用PHPExcel验证上载的Excel文件数据的最佳方法

时间:2015-11-12 15:01:39

标签: php codeigniter phpexcel

检查数组中包含的数据的最有效方法是什么

我想通过以下方式验证:

  1. 如果单元格a和b是字符串
  2. 如果单元格c和d是数字
  3. 如果单元格为空
  4. 那么如何最好地捕获错误并将其显示给用户?

    我正在使用codeigniter和PHPExcel库

    我目前在哪里的一个例子

        public function read_excel()            
        {
            $this->load->library('excel');
            $inputFileName = 'test.xlsx';
            /**  Identify the type of $inputFileName  **/
            $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            /**  Advise the Reader that we only want to load cell data  **/
            $objReader->setReadDataOnly(true);
            /**  Load $inputFileName to a PHPExcel Object  **/
            $objPHPExcel = $objReader->load($inputFileName);
            $sheet = $objPHPExcel->getSheet(0); 
            $highestRow = $sheet->getHighestRow(); 
            $highestColumn = $sheet->getHighestColumn();
    
    
            //  Loop through each row of the worksheet
            for ($row = 2; $row <= $highestRow; $row++){     //  Read a row of data into an array
                $rowData = $sheet->rangeToArray('A'.$row.':'.$highestColumn.$row,NULL,TRUE,FALSE);
    
                $cella = strtoupper($rowData[0][0]);
                $cellb = strtoupper($rowData[0][1]);
                $cellc = $rowData[0][2];
                $celld = $rowData[0][3];
            }
    
    
        }
    

    要回答我自己的问题,我最终选择了以下

                    if (!isset($rowData[0][0],$rowData[0][1],$rowData[0][2])) {
    
                    echo "error cells a-c are required.";
                }
    
    
    
                for ($i=0; $i <$columns ; $i++) { 
                    switch ($rowData[0][$i]) {
                        case (is_numeric($rowData[0][$i])):
                            filter_var($rowData[0][$i],FILTER_SANITIZE_NUMBER_INT);
                            echo $rowData[0][$i];
                            echo "</br>";
                            break;
                        case (is_string($rowData[0][$i])):
                            $rowData[0][$i] = preg_replace("/[^A-Za-z0-9\-]/"," ",$rowData[0][$i]);
                            break;
                    }
    
                }
    

0 个答案:

没有答案