在使用phpExcel导入代码点火器中的数据库之前,先验证单元格数据

时间:2018-08-12 14:21:32

标签: php codeigniter phpexcel

我很难解决这个问题。

我刚刚开始使用phpExcel库。我正在尝试构建一个允许用户将其数据导入数据库的功能。我正在使用Code Igniter的批处理插入功能将数据发送到数据库。我可以使用它,但是我需要对范围内的某些单元格设置一些规则。例如,某些单元格不能为空,其他单元格不能为数字,依此类推。 这是我到目前为止所做的:

public function import_students_action() {
            //config for file uploads
            $config['upload_path']          = './assets/uploads/imports/students'; //path to save the files
            $config['allowed_types']        = 'xls|xlsx';  //extensions which are allowed
            $config['max_size']             = 1024 * 2; //image size cannot exceed 2MB
            $config['file_ext_tolower']     = TRUE; //force file extension to lower case
            $config['remove_spaces']        = TRUE; //replace space in file names with underscores to avoid break
            $config['detect_mime']          = TRUE; //detect type of file to avoid code injection
            $this->load->library('upload', $config);

            if ( $_FILES['excel_file']['name'] == "" ) { //file is not selected
                $this->session->set_flashdata('status_msg_error', "No file selected!");
                $this->import_students(); //reload page

            } elseif ( ( ! $this->upload->do_upload('excel_file')) && ($_FILES['excel_file']['name'] != "") ) {     
                //upload does not happen when file is selected
                $error = array('error' => $this->upload->display_errors());
                $this->import_students($error); //reload page with upload errors

            } else { //file is selected, upload happens, everyone is happy

                $path = $_FILES["excel_file"]["tmp_name"];
                $object = PHPExcel_IOFactory::load($path);

                $last_name = "";
                $first_name = "";
                $class = "";
                $highestRow = "";

                foreach ($object->getWorksheetIterator() as $worksheet) {
                    $highestRow = $worksheet->getHighestRow(); //last row with data
                    $highestColumn = $worksheet->getHighestColumn(); //last column with data

                    //start loop from 2nd row. Row 1 is title row
                    for ($row=2; $row<=$highestRow; $row++) {
                        $last_name = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
                        $first_name = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
                        $class = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
                        $data[] = array(
                            'school_id'  => school_id,
                            'last_name'  => $last_name,
                            'first_name'   => $first_name,
                            'class'    => $class,
                        );
                    }
                }

                //validation rules
                if  ($last_name == NULL || $first_name == NULL || $class == NULL) {
                    $this->session->set_flashdata('status_msg_error', 'Import failed! Ensure all required fields are filled properly.');
                } else {
                    $this->data_import_model->import_students($data);
                    $highestRow = $highestRow - 1; //total rows with content - 1 (title row)
                    $students = ($highestRow == 1) ? 'student' : 'students';
                    $this->session->set_flashdata('status_msg', "{$highestRow} {$students} imported successfully.");
                }
                redirect('data_import/import_students');
            } 
        }

使用上述代码,即使所需单元格为空,insert命令也会执行。如果必需的单元格为空,我需要它引发错误。如果我做对了,可以应用其他规则。另外,我想知道如何将规则和错误消息作为数组应用。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要使代码停止执行或重定向到上一页, 我还使用了方法empty,因为它更方便地检测空值和空值。   检查以下代码:

 public function import_students_action() {
                //config for file uploads
                $config['upload_path']          = './assets/uploads/imports/students'; //path to save the files
                $config['allowed_types']        = 'xls|xlsx';  //extensions which are allowed
                $config['max_size']             = 1024 * 2; //image size cannot exceed 2MB
                $config['file_ext_tolower']     = TRUE; //force file extension to lower case
                $config['remove_spaces']        = TRUE; //replace space in file names with underscores to avoid break
                $config['detect_mime']          = TRUE; //detect type of file to avoid code injection
                $this->load->library('upload', $config);

                if ( $_FILES['excel_file']['name'] == "" ) { //file is not selected
                    $this->session->set_flashdata('status_msg_error', "No file selected!");
                    $this->import_students(); //reload page

                } elseif ( ( ! $this->upload->do_upload('excel_file')) && ($_FILES['excel_file']['name'] != "") ) {     
                    //upload does not happen when file is selected
                    $error = array('error' => $this->upload->display_errors());
                    $this->import_students($error); //reload page with upload errors

                } else { //file is selected, upload happens, everyone is happy

                    $path = $_FILES["excel_file"]["tmp_name"];
                    $object = PHPExcel_IOFactory::load($path);

                    $last_name = "";
                    $first_name = "";
                    $class = "";
                    $highestRow = "";

                    foreach ($object->getWorksheetIterator() as $worksheet) {
                        $highestRow = $worksheet->getHighestRow(); //last row with data
                        $highestColumn = $worksheet->getHighestColumn(); //last column with data

                        //start loop from 2nd row. Row 1 is title column
                        for ($row=2; $row<=$highestRow; $row++) {
                            $last_name = trim($worksheet->getCellByColumnAndRow(0, $row)->getValue());
                            $first_name = trim($worksheet->getCellByColumnAndRow(1, $row)->getValue());
                            $class = trim($worksheet->getCellByColumnAndRow(2, $row)->getValue());
                            $data[] = array(
                                'school_id'  => school_id,
                                'last_name'  => $last_name,
                                'first_name'   => $first_name,
                                'class'    => $class,
                            );
                        }
                    }

                    //validation rules
                    if  (empty($last_name) || empty($first_name) || empty($class) ) {
                        $this->session->set_flashdata('status_msg_error', 'Import failed! Ensure all required fields are filled properly.');
redirect('data_import/error');
exit;
                    } else {
                        $this->data_import_model->import_students($data);
                        $highestRow = $highestRow - 1; //total rows with content - 1 (title row)
                        $students = ($highestRow == 1) ? 'student' : 'students';
                        $this->session->set_flashdata('status_msg', "{$highestRow} {$students} imported successfully.");
                    }
                    redirect('data_import/import_students');
                } 
            }