Beispiel #1
3
 public function main($UrlAppend = NULL, $get = NULL, $post = NULL)
 {
     if ($this->_isPost()) {
         $data = new Spreadsheet_Excel_Reader();
         $data->setOutputEncoding('utf-8');
         $file = $this->_upload();
         $data->read($file["path"]);
         $keyArr = array();
         for ($a = 1; $a < 1000; $a++) {
             if ($data->sheets[0]['cells'][1][$a] != "") {
                 array_push($keyArr, $data->sheets[0]['cells'][1][$a]);
             }
         }
         $dataList = array();
         for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
             $valueArr = array();
             for ($b = 0; $b < count($keyArr); $b++) {
                 if ($keyArr[$b] == "key") {
                     $key = $data->sheets[0]['cells'][$i][$b + 1];
                 } else {
                     $valueArr[$keyArr[$b]] = $data->sheets[0]['cells'][$i][$b + 1];
                 }
             }
             $dataList[$key] = $valueArr;
         }
         $this->_f($_POST["FileName"], $dataList);
     }
     return $this->_assign;
 }
 function getAll()
 {
     $reader = new Spreadsheet_Excel_Reader();
     $reader->setUTFEncoder('iconv');
     $reader->setOutputEncoding('UTF-8');
     $reader->read($this->filename);
     $data = array();
     $index_row = 1;
     if ($this->have_header) {
         $index_row = 2;
     }
     $iterator = -1;
     for ($i = $index_row; $i <= $reader->sheets[$this->sheet_index]['numRows']; $i++) {
         $iterator++;
         $data[$iterator] = array();
         for ($j = 1; $j <= $reader->sheets[$this->sheet_index]['numCols']; $j++) {
             if ($this->have_header) {
                 $data[$iterator][$this->headers[$j - 1]] = $reader->sheets[0]['cells'][$i][$j];
             } else {
                 $data[$iterator][$j - 1] = $reader->sheets[0]['cells'][$i][$j];
             }
         }
     }
     return $data;
 }
Beispiel #3
1
 function upload_bulk_courses()
 {
     $data['user_id'] = $this->tank_auth->get_admin_user_id();
     $config['upload_path'] = $this->excel_path;
     $config['allowed_types'] = 'xls';
     //$config['max_size']    = '10000';
     $this->load->library('upload', $config);
     if (!$this->upload->do_upload()) {
         $data['err_msg'] = $this->upload->display_errors();
         $this->load->view('admin/show_error', $data);
     } else {
         $this->load->library('Spreadsheet_Excel_Reader');
         $path = $this->excel_path . '/' . $_FILES['userfile']['name'];
         $data1 = new Spreadsheet_Excel_Reader();
         $data1->read($path);
         error_reporting(E_ALL ^ E_NOTICE);
         for ($j = 1; $j < $data1->sheets[0]['numRows']; $j++) {
             $prog_data = array();
             for ($i = 1; $i <= $data1->sheets[0]['numCols']; $i++) {
                 $res = $data1->sheets[0]['cells'][$j + 1][$i];
                 //for finding program education level id by its name
                 if ($i == 2) {
                     $res = $this->courses->educ_lvl_id_by_name($data1->sheets[0]['cells'][$j + 1][$i]);
                 }
                 if ($i == 4) {
                     $res = $this->courses->area_of_intrst_id_by_name($data1->sheets[0]['cells'][$j + 1][$i]);
                 }
                 $prog_data[] = $res;
             }
             $pro = array('prog_title' => $prog_data[0], 'educ_level_id' => $prog_data[1], 'course_name' => $prog_data[2], 'prog_parent_id' => $prog_data[3], 'createdby' => $data['user_id']);
             /*$pro=array('prog_title' =>$prog_data[0],
             					'educ_level_id'=>$prog_data[1],
             					'course_name'=>$prog_data[2],
             					'prog_parent_id'=>$prog_data[3],
             					'intake1'=>$prog_data[4],
             					'intake2'=>$prog_data[5],
             					'program_duration1'=>$prog_data[6],
             					'tution_fee1'=>$prog_data[7],
             					'program_duration2'=>$prog_data[8],
             					'tution_fee2'=>$prog_data[9],
             					'experience_required'=>$prog_data[10],
             					'gpa_required'=>$prog_data[11],
             					'per_required'=>$prog_data[12],
             					'program_detail'=>$prog_data[13],
             					'createdby'=>$data['user_id']
             					);
             		*/
             $this->db->insert('program', $pro);
             redirect('admincourses/manage_courses/bcus');
         }
         //echo $data->sheets[0]['numRows'];
     }
 }
function ABSSAV()
{
    $inFile = $_REQUEST['inFile'];
    echo "Filename is: {$inFile}<br>";
    require_once 'Excel/reader.php';
    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding('CP1251');
    $data->read($inFile);
    error_reporting(E_ALL ^ E_NOTICE);
    $Target_Database = 'binawan';
    $Target_Table = $Target_Database . '.ruang';
    $Target_KodeID = "BINAWAN";
    $s = "TRUNCATE TABLE {$Target_Table}";
    $r = _query($s);
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        $w = array();
        $w['RuangID'] = trim($data->sheets[0]['cells'][$i][2]);
        $w['Nama'] = trim($data->sheets[0]['cells'][$i][3]);
        $w['Kapasitas'] = trim($data->sheets[0]['cells'][$i][4]);
        $w['KapasitasUjian'] = trim($data->sheets[0]['cells'][$i][4]);
        $w['KolomUjian'] = trim($data->sheets[0]['cells'][$i][5]);
        $w['KampusID'] = trim($data->sheets[0]['cells'][$i][6]);
        $w['Lantai'] = trim($data->sheets[0]['cells'][$i][7]);
        $w['RuangKuliah'] = trim($data->sheets[0]['cells'][$i][8]);
        $s = "insert into {$Target_Table}\r\n          (RuangID, Nama, Kapasitas, KapasitasUjian, KolomUjian, KampusID, Lantai, KodeID, RuangKuliah, UntukUSM\r\n\t      )\r\n          values\r\n          ('{$w['RuangID']}', '{$w['Nama']}', '{$w['Kapasitas']}', '{$w['KapasitasUjian']}', '{$w['KolomUjian']}', '{$w['KampusID']}', '{$w['Lantai']}', 'BINAWAN', '{$w['RuangKuliah']}', '{$w['RuangKuliah']}'\r\n\t      )";
        $r = _query($s);
    }
    echo "<script>window.location = '?{$mnux}={$_SESSION['mnux']}'</script>";
}
Beispiel #5
0
 /**
   Helper for xls files. See fileToArray()
 */
 public static function xlsToArray($filename, $limit)
 {
     if (!class_exists('Spreadsheet_Excel_Reader')) {
         include_once dirname(__FILE__) . '/../../src/Excel/xls_read/reader.php';
     }
     $data = new \Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('ISO-8859-1');
     $data->read($filename);
     $sheet = $data->sheets[0];
     $rows = $sheet['numRows'];
     $cols = $sheet['numCols'];
     $ret = array();
     for ($i = 1; $i <= $rows; $i++) {
         $line = array();
         for ($j = 1; $j <= $cols; $j++) {
             if (isset($sheet['cells'][$i]) && isset($sheet['cells'][$i][$j])) {
                 $line[] = $sheet['cells'][$i][$j];
             } else {
                 $line[] = '';
             }
         }
         $ret[] = $line;
         if ($limit != 0 && count($ret) >= $limit) {
             break;
         }
     }
     return $ret;
 }
function updateDB($startIndex, $endIndex)
{
    //need to copy the code that does the excel reading
    $analysisData = new Spreadsheet_Excel_Reader();
    // Set output Encoding.
    $analysisData->setOutputEncoding('CP1251');
    $inputFileName = 'ReverseGeoCodingForStopsVerification.xls';
    $analysisData->read($inputFileName);
    error_reporting(E_ALL ^ E_NOTICE);
    $numRows = $analysisData->sheets[0]['numRows'];
    $numCols = $analysisData->sheets[0]['numCols'];
    //echo $numRows.",".$numCols;
    $strRoute = '<Routes>';
    for ($i = $startIndex; $i <= $endIndex; $i++) {
        $stopId = $analysisData->sheets[0]['cells'][$i][1];
        $StopName = $analysisData->sheets[0]['cells'][$i][2];
        $Buses = $analysisData->sheets[0]['cells'][$i][3];
        $latitude = $analysisData->sheets[0]['cells'][$i][4];
        $longitude = $analysisData->sheets[0]['cells'][$i][5];
        $strRoute = $strRoute . '<Route>';
        $routeDetails = htmlentities(trim($StopName)) . ":" . $latitude . ":" . $longitude;
        //echo $routeDetails."<br/>";
        $strRoute = $strRoute . '<RouteDetails>' . $routeDetails . '</RouteDetails>';
        $strRoute = $strRoute . '</Route>';
    }
    $strRoute = $strRoute . '</Routes>';
    echo $strRoute;
}
 public function localUploadSNExcel()
 {
     $return = $this->localUpload(array('xls'));
     if ($return['error']) {
         $this->error($return['msg']);
     } else {
         $data = new Spreadsheet_Excel_Reader();
         // 设置输入编码 UTF-8/GB2312/CP936等等
         $data->setOutputEncoding('UTF-8');
         $data->read(str_replace('http://' . $_SERVER['HTTP_HOST'], $_SERVER['DOCUMENT_ROOT'], $return['msg']));
         chmod(str_replace('http://' . $_SERVER['HTTP_HOST'], $_SERVER['DOCUMENT_ROOT'], $return['msg']), 0777);
         //
         $sheet = $data->sheets[0];
         $rows = $sheet['cells'];
         if ($rows) {
             $i = 0;
             foreach ($rows as $r) {
                 if ($i != 0) {
                     $db = M('Lottery_record');
                     $where = array('token' => $this->token, 'lid' => intval($_POST['lid']), 'sn' => trim($r[1]));
                     $check = $db->where($where)->find();
                     if (!$check) {
                         $where['prize'] = intval($r['2']);
                         $db->add($where);
                     }
                 }
                 $i++;
             }
         }
         $this->success('操作完成');
     }
 }
function ABSSAV()
{
    $inFile = $_REQUEST['inFile'];
    require_once 'Excel/reader.php';
    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding('CP1251');
    $data->read($inFile);
    error_reporting(E_ALL ^ E_NOTICE);
    $Target_Database = 'binawan';
    $Target_Table = $Target_Database . 'mhsw';
    $Target_KodeID = "BINAWAN";
    $s = "TRUNCATE TABLE ";
    $r = _query($s);
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        $w = array();
        $w['MhswID'] = trim($data->sheets[0]['cells'][$i][1]);
        $w['TahunID'] = trim($data->sheets[0]['cells'][$i][2]);
        $w['Nama'] = trim($data->sheets[0]['cells'][$i][3]);
        $w['Kelamin'] = trim($data->sheets[0]['cells'][$i][4]);
        $w['TempatLahir'] = trim($data->sheets[0]['cells'][$i][5]);
        $w['TanggalLahir'] = trim($data->sheets[0]['cells'][$i][6]);
        $w['Agama'] = trim($data->sheets[0]['cells'][$i][7]);
        $w['Alamat'] = trim($data->sheets[0]['cells'][$i][8]);
        $s = "insert into {$Target_Database}\r\n          (MhswID, Login, LevelID, Password, PMBID, \r\n\t\t   TahunID, KodeID, Nama, \r\n\t\t   Foto, StatusMhswID, ProgramID, ProdiID, KelasID,\r\n\t\t   Kelamin, TempatLahir, TanggalLahir, Agama, Alamat, \r\n\t\t   Kota, RT, RW, KodePos, Propinsi, Negara, \r\n\t\t   Telepon, Handphone \r\n\t      )\r\n          values\r\n          ('{$w['MhswID']}', '{$w['Login']}', '120', '{$w['Password']}', '{$w['PMBID']}', \r\n\t\t   '{$w['TahunID']}', '{$Target_KodeID}', '{$w['Nama']}', \r\n\t\t   '{$w['Foto']}', '{$w['StatusMhswID']}', '{$w['ProgramID']}', '{$w['ProdiID']}', '{$w['KelasID']}',\r\n\t\t   '{$w['Kelamin']}', '{$w['TempatLahir']}', '{$w['TanggalLahir']}', '{$w['Agama']}', '{$w['Alamat']}', \r\n\t\t   '{$w['Kota']}', '{$w['RT']}', '{$w['RW']}', '{$w['KodePos']}', '{$w['Propinsi']}', '{$w['Negara']}', \r\n\t\t   '{$w['Telepon']}', '{$w['Handphone']}' \r\n\t      )";
        $r = _query($s);
    }
    echo "<script>window.location = '?{$mnux}={$_SESSION['mnux']}'</script>";
}
 public function add_in_mysql()
 {
     if (!empty($_FILES['efile']['name'])) {
         $exname = strtolower(substr($_FILES['efile']['name'], strrpos($_FILES['efile']['name'], '.') + 1));
         $uploadfile = $this->getnames($exname);
         //上传后文件所在的路径
         @move_uploaded_file($_FILES['efile']['tmp_name'], $uploadfile);
     }
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('utf-8');
     $data->read($uploadfile);
     //读取要导入数据库的文件
     error_reporting(E_ALL ^ E_NOTICE);
     $Stu = D("Stu");
     //$User->startTrans();//启动事务;
     $filed = C("excle");
     //获取字段对应的列
     for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
         $col = $data->sheets[0]['cells'][$i];
         $arr = array("stuno" => $col[$filed["stuno"]], "stuname" => $col[$filed["stuname"]], "password" => $col[$filed["password"]], "sex" => $col[$filed["sex"]], "idcard" => $col[$filed["idcard"]], "classno" => $col[$filed["classno"]], "college" => "1");
         $Stu->create($arr);
         echo $Stu->getError() . "<br/>";
         if (!$Stu->add()) {
             $Stu->rollback();
             //不成功,回滚
             echo "导入失败回滚";
             return;
         }
         echo $arr["stuno"] . "导入成功<br/>";
     }
     $Stu->commit();
     //成功提交
 }
Beispiel #10
0
 function doimport()
 {
     $file_name = $_GET['province_id'] . ".xls";
     if ($file_name != '') {
         //$ext = pathinfo($_FILES['filename']['name'], PATHINFO_EXTENSION);
         //echo $file_name = 'nursery.'.$ext;
         $uploaddir = 'import/tmp/';
         $fpicname = $uploaddir . $file_name;
         ///move_uploaded_file($_FILES['filename']['tmp_name'], $fpicname);
         require_once 'include/Excel/reader.php';
         $data = new Spreadsheet_Excel_Reader();
         $data->setOutputEncoding('UTF-8');
         $data->read($fpicname);
         error_reporting(E_ALL ^ E_NOTICE);
         $index = 0;
         for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
             $amphur = new Amphur();
             $amphur = $amphur->where(" amphur_name ='" . trim($data->sheets[0]['cells'][$i][1]) . "'")->get();
             $import[$index]['province_id'] = $_POST['province_id'];
             $import[$index]['amphur_id'] = $amphur->id;
             $import[$index]['name'] = trim($data->sheets[0]['cells'][$i][2]);
             $index++;
             if ($amphur->id > 0) {
                 $_POST['province_id'] = $_GET['province_id'];
                 $_POST['amphur_id'] = $amphur->id;
                 $_POST['name'] = trim($data->sheets[0]['cells'][$i][2]);
                 $nursery = new Nursery_Tmp();
                 $nursery->from_array($_POST);
                 $nursery->save();
             }
         }
     }
 }
Beispiel #11
0
 function getDataFromExcel($filename)
 {
     $uimap = new Spreadsheet_Excel_Reader();
     $uimap->read($this->path . "\\data\\uimap\\" . $filename . ".xls");
     $s = 0;
     foreach ($uimap->boundsheets as $ar) {
         $i = 2;
         while ($i <= $uimap->sheets[$s]['numRows']) {
             if (!empty($uimap->sheets[$s]['cells'][$i][2]) && !empty($uimap->sheets[$s]['cells'][$i][3]) && strtolower($ar['name']) != 'datamap') {
                 $this->sheets[strtolower($ar['name'])][strtolower($uimap->sheets[$s]['cells'][$i][2])] = $uimap->sheets[$s]['cells'][$i][3];
             } elseif (!empty($uimap->sheets[$s]['cells'][$i][2]) && strtolower($ar['name']) == 'datamap') {
                 $datafile = new Spreadsheet_Excel_Reader();
                 $datafile->read($this->path . "\\" . $uimap->sheets[$s]['cells'][$i][3]);
                 $j = 2;
                 while ($j <= $datafile->sheets[0]['numRows']) {
                     if (!empty($datafile->sheets[0]['cells'][$j][2])) {
                         if (empty($datafile->sheets[0]['cells'][$j][4])) {
                             $this->datamap[strtolower($datafile->sheets[0]['cells'][$j][2])] = $datafile->sheets[0]['cells'][$j][3];
                         } else {
                             $y = 3;
                             while (!empty($datafile->sheets[0]['cells'][$j][$y])) {
                                 $this->datamap[strtolower($datafile->sheets[0]['cells'][$j][2])][] = $datafile->sheets[0]['cells'][$j][$y];
                                 $y++;
                             }
                         }
                     }
                     $j++;
                 }
             }
             $i++;
         }
         $s++;
     }
     $this->uimap = $this->sheets;
 }
Beispiel #12
0
 function do_upload()
 {
     $config['upload_path'] = './upload/';
     $config['allowed_types'] = 'php|txt|xls|xml';
     $config['max_size'] = '1000000';
     //$config['max_width']  = '1024';
     //$config['max_height']  = '768';
     $this->load->library('upload', $config);
     if (!$this->upload->do_upload()) {
         $error = array('error' => $this->upload->display_errors());
         //$this->load->view('header');
         $this->load->view('upload_view', $error);
         //$this->load->view('footer');
     } else {
         $data = array('upload_data' => $this->upload->data());
         $this->load->library('Excel/spreadsheet_Excel_Reader');
         //require_once 'Excel/reader.php';
         // ExcelFile($filename, $encoding);
         $excel = new Spreadsheet_Excel_Reader();
         // Set output Encoding.
         $excel->setOutputEncoding('CP1251');
         //lecture du fichier excel
         //chmod('./upload/' . $data['upload_data']['file_name'], 0777);
         $excel->read('./upload/' . $data['upload_data']['file_name']);
         //$liste = array($excel->sheets[0]['numRows'],2);
         $array = $excel->sheets[0]['cells'];
         $temp = array_shift($array);
         var_dump($array);
         //$this->data_model->insert_entry($array);
         $this->load->view('upload_success', $data);
     }
 }
function readRoom($file, $table, $pos)
{
    require_once "conn.php";
    $sql = "TRUNCATE TABLE {$table}";
    if ($mysqliObj->query($sql)) {
        echo "truncate success" . "</br>";
    }
    require_once 'Excel/reader.php';
    // ExcelFile($filename, $encoding);
    $data = new Spreadsheet_Excel_Reader();
    // Set output Encoding.
    // $data->setOutputEncoding('CP936');
    $data->setOutputEncoding('gbk');
    $data->read($file);
    error_reporting(E_ALL ^ E_NOTICE);
    //$data->sheets[0]['numRows']
    for ($i = $pos; $i <= $data->sheets[0]['numRows']; $i++) {
        $msg1 = $data->sheets[0]['cells'][$i][1];
        $msg2 = $data->sheets[0]['cells'][$i][2];
        $msg3 = $data->sheets[0]['cells'][$i][3];
        $sql = "INSERT INTO  {$table} (`roomId` ,`type` ,`price` )\n\t\t\t\tVALUES ('{$msg1}',  '{$msg2}',  '{$msg3}')";
        if (!is_null($data->sheets[0]['cells'][$i][1])) {
            $mysqliObj->query($sql);
        }
    }
    $mysqliObj->close();
}
Beispiel #14
0
function popola($file, $id_associazione)
{
    $data = new Spreadsheet_Excel_Reader();
    //$data->setOutputEncoding('CP1251'); //UTF-8
    $data->setOutputEncoding('UTF-8');
    $data->read($file);
    error_reporting(E_ALL ^ E_NOTICE);
    $counter = 0;
    $counterP = 0;
    $log_error = new log();
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        $counterP++;
        echo $counterP . " ";
        if ($counterP % 100 == 0) {
            echo "\n  Processati: " . $counterP . "\n";
        }
        ob_flush();
        flush();
        $query = "INSERT into soci (nome,mail) values ";
        $query .= "(";
        echo $data->sheets[0]['cells'][$i][1] . "   ... \n";
        $actual_element = trim($data->sheets[0]['cells'][$i][1], " \t\n\r\v,;");
        echo $actual_element;
        $actual_element = mysql_real_escape_string($actual_element);
        $actual_element2 = trim($data->sheets[0]['cells'][$i][2], " \t\n\r\v,;");
        $mail = mysql_real_escape_string($actual_element2);
        $query .= "'" . $actual_element . "','" . $mail . "'";
        // Aggiungi user e password
        //$query.="'".(($email=="") ? getUniqueCode(10) : $email)."','".getUniqueCode(10)."',$id_associazione";
        $query .= ")";
        //validate email
        if (!Swift_Validate::email($actual_element2)) {
            //validate email, log error
            $log_error->scrivi_popola($actual_element . "\t" . $mail);
        } else {
            //insert into DB
            $result = mysql_query("SELECT id FROM soci WHERE mail='" . $mail . "'");
            if ($riga = mysql_fetch_assoc($result)) {
                //if the mail is  already in the database
                $int_id = $riga['id'];
            } else {
                if (!mysql_query($query)) {
                    //insert new record
                    echo "ti è andata male   ";
                    echo $query;
                    return false;
                }
                $int_id = mysql_insert_id();
                $counter++;
            }
            if ($id_associazione > 0) {
                mysql_query("INSERT into interessi_soci (id_socio,id_interesse) values ('{$int_id}','{$id_associazione}')");
            }
        }
    }
    $log_error->close_popola();
    //return $data->sheets[0]['numRows']-1;
    return "<BR>Letti " . $counterP . " e inseriti (non duplicati) " . $counter;
}
function get_student_schedule($filename, $teacherSchedule)
{
    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding('UTF8');
    $data->setUTFEncoder('mb');
    $data->read($filename);
    return get_result_student($data, $teacherSchedule);
}
Beispiel #16
0
/**
 * Handle and read uploaded file
 * @param array - fileArray from form
 * @param array - postArray from form
 */
function handleUpload($_FILES, $_POST)
{
    require_once "JotForm.php";
    $path = mktime() . '_' . $_FILES['file']['name'];
    $key = $_POST['APIkey'];
    $form = $_POST['formID'];
    $jot = new JotForm($key);
    $error = "";
    if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
        $fileType = getFileType($path);
        $columns = array();
        if ($fileType == 'csv') {
            if (($handle = fopen($path, "r")) !== FALSE) {
                if (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    foreach ($data as $title) {
                        array_push($columns, $title);
                    }
                }
                $error = 'File must contain at least two rows - the first represents the field titles';
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $error = '';
                    $result = $jot->createFormSubmissions($form, writeData($data, $columns));
                }
                fclose($handle);
            } else {
                $error = 'Could not open file';
            }
        } else {
            require_once 'Excel/reader.php';
            $excel = new Spreadsheet_Excel_Reader();
            $excel->read($path);
            if ($excel->sheets[0]['numRows'] > 1) {
                for ($i = 1; $i <= $excel->sheets[0]['numCols']; $i++) {
                    $title = $excel->sheets[0]['cells'][1][$i];
                    array_push($columns, $title);
                }
                for ($i = 2; $i <= $excel->sheets[0]['numRows']; $i++) {
                    $data = array();
                    for ($j = 1; $j <= $excel->sheets[0]['numCols']; $j++) {
                        array_push($data, $excel->sheets[0]['cells'][$i][$j]);
                    }
                    $jot->createFormSubmissions($form, writeData($data, $columns));
                }
            } else {
                $error = 'File must contain at least two rows - the first represents the field titles';
            }
        }
    } else {
        $error = 'No File Found';
    }
    if (strlen($error) > 0) {
        return $error;
    } else {
        return 'none';
    }
}
Beispiel #17
0
function readxlsmain($file)
{
    $d = new Spreadsheet_Excel_Reader();
    $d->setOutputEncoding('utf-8');
    $d->read($file);
    $data = array();
    $data['boundsheets'] =& $d->boundsheets;
    $data['sheets'] =& $d->sheets;
    return $data;
}
Beispiel #18
0
function process_file($filename, &$tempname)
{
    global $_SGLOBAL;
    $isfile = 1;
    $data = new Spreadsheet_Excel_Reader();
    //exit('adsf');
    $data->setOutputEncoding('gbk');
    $data->read($filename);
    $tempname = date("Y-m-d") . '_download_' . rand() . '.xls';
    $filedownload = S_ROOT . './plugin/invite/download/' . $tempname;
    //初始化一个反馈结果的文件
    require_once S_ROOT . './plugin/invite/phpwritexcel/Writer.php';
    $workbook = new Spreadsheet_Excel_Writer($filedownload);
    $worksheet =& $workbook->addWorksheet('Sheet1');
    $worksheet->setInputEncoding('utf-8');
    $format_column =& $workbook->addformat(array('Size' => 9, 'Bold' => 1));
    //读取结果文件的信息
    $rows = 0;
    $recordindex = array('realname', 'sex', 'birthday', 'otheremail', 'academy', 'collegeid', 'class', 'mobile', 'unit');
    $record = array('好友姓名(必填)', '好友性别', '生日(8位)', '邮箱(必填)', '学院', '学号', '班别', '手机(必填)', '所在单位', '备注');
    $dataindexinfo = array();
    encode_record(&$record);
    input_downloadfile($worksheet, $rows, $record, $format_column);
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        //以下注释的for循环打印excel表数据
        $datainfo = array();
        //$datainfo = array('name', 'sex', 'birthday', 'otheremail', 'academy', 'collegeid', 'class', 'mobile', 'unit');
        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            $datainfo[$j - 1] = $data->sheets[0]['cells'][$i][$j];
            $dataindexinfo[$recordindex[$j - 1]] = $data->sheets[0]['cells'][$i][$j];
        }
        //var_dump($datainfo[0]);
        //检查记录的正确性
        $nopass = checkinfo($datainfo[0], $datainfo[2], $datainfo[3], $datainfo[7], $isfile);
        if (!empty($nopass)) {
            //没有通过的记录加入到一个新文件中
            $datainfo[$j - 1] = $nopass;
            encode_record(&$datainfo);
            //var_dump($datainfo);
            //var_dump($rows);
            input_downloadfile($worksheet, &$rows, $datainfo, $format_column);
            continue;
        }
        //邀请处理
        //var_dump($dataindexinfo);
        inserttable('baseprofile', $dataindexinfo, 1);
        //var_dump($datainfo);
        invite_alumni($datainfo);
    }
    $workbook->close();
    return $rows;
}
Beispiel #19
0
 public function _batchDeal()
 {
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('utf-8');
     $file = $this->_upload();
     $data->read($file["path"]);
     for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
         $sendData = array('WorldID' => intval($data->sheets[0]['cells'][$i][1]), 'IsAllPlayer' => intval(0), 'PlayerID' => trim($data->sheets[0]['cells'][$i][2]), 'Title' => trim($data->sheets[0]['cells'][$i][3]), 'Content' => trim($data->sheets[0]['cells'][$i][4]), 'IsPack' => intval($data->sheets[0]['cells'][$i][5]), 'ItemID' => intval($data->sheets[0]['cells'][$i][6]), 'ItemNum' => intval($data->sheets[0]['cells'][$i][7]), 'IsBinded' => intval($data->sheets[0]['cells'][$i][8]), 'TimeDurableType' => intval($data->sheets[0]['cells'][$i][9]), 'TimeDurable' => intval(strtotime($data->sheets[0]['cells'][$i][10])), 'ImproveLevel' => intval($data->sheets[0]['cells'][$i][11]), 'AttachAttribute' => trim($data->sheets[0]['cells'][$i][12]), 'Money' => trim($data->sheets[0]['cells'][$i][13]), 'Exp' => intval($data->sheets[0]['cells'][$i][14]));
         $returnData .= "[" . $i . "]" . $this->addApply($sendData) . "<br/>";
     }
     $URL_CsIndex = Tools::url('Apply', 'CsIndex');
     $URL_CsAll = Tools::url('Apply', 'CsAll');
     $showMsg = $returnData;
     $showMsg .= "<a href='{$URL_CsIndex}'>客服审核列表</a><br>";
     $showMsg .= "<a href='{$URL_CsAll}'>客服审核列表(全部)</a>";
     $this->jump($showMsg, 1, 1, false);
     die($returnData);
 }
 public static function readXLS($file)
 {
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('UTF-8');
     //设置输出的编码为utf8
     $ret = $data->read($file);
     //要读取的excel文件地址
     if ($ret == -1) {
         $array = false;
     } else {
         for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
             for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
                 $array[$i - 1][$j - 1] = $data->sheets[0]['cells'][$i][$j];
             }
         }
     }
     return $array;
 }
 public static function leerMarcadoresExcel($fichero)
 {
     $leidos = array();
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('CP1251');
     $data->read($fichero);
     //Se comienza de indice 2 para un excel donde la primera row sea los titulos de las columnas
     for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
         $objeto = new Marcador();
         $objeto->lat = $data->sheets[0]['cells'][$i][1];
         $objeto->lng = $data->sheets[0]['cells'][$i][2];
         $objeto->nombre = $data->sheets[0]['cells'][$i][3];
         $objeto->direccion = $data->sheets[0]['cells'][$i][4];
         $objeto->codPostal = $data->sheets[0]['cells'][$i][5];
         array_push($leidos, $objeto);
     }
     return $leidos;
 }
Beispiel #22
0
 function _fallbackExcelReader($sFilename, $sTempFilename)
 {
     require_once KT_DIR . '/thirdparty/excelreader/Excel/reader.php';
     $reader = new Spreadsheet_Excel_Reader();
     $reader->setOutputEncoding('UTF-8');
     $reader->read($sFilename);
     $t = fopen($sTempFilename, "w");
     foreach ($reader->sheets as $aSheet) {
         for ($i = 1; $i <= $aSheet['numRows'] && $i <= 1000; $i++) {
             for ($j = 1; $j <= $aSheet['numCols'] && $j <= 1000; $j++) {
                 fwrite($t, $aSheet['cells'][$i][$j] . " ");
             }
             fwrite($t, "\n");
         }
         fwrite($t, "\n\n\n");
     }
     fclose($t);
     return file_get_contents($sTempFilename);
 }
Beispiel #23
0
 public function dealExcel($file)
 {
     include BASE_DATA_PATH . "/Excel/reader.php";
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('GBK');
     $data->read($file);
     $xls_arr = array();
     for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
         for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
             $val = iconv("gb2312", "utf-8//IGNORE", $data->sheets[0]['cells'][$i][$j]);
             $xls_arr[$i][$j] = $val;
         }
         echo "\n";
     }
     if (!empty($xls_arr)) {
         return $this->insertExcelData($xls_arr);
     } else {
         return true;
     }
 }
 public static function parseexcel($filepath, $source = 'GBK', $target = 'UTF-8')
 {
     $data = array();
     require PATH_APPLICATION . '/pm_excel_reader.class.php';
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('GBK');
     @$data->read($filepath);
     $dataarray = array();
     for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
         for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
             $dataarray[$i][$j] = $data->sheets[0]['cells'][$i][$j];
         }
     }
     if ($source == $target) {
         $data = array_slice($dataarray, 1);
     } else {
         $dataarray = ck_iconv_deep($source, $target, $dataarray);
         $data = array_slice($dataarray, 1);
     }
     return $data;
 }
Beispiel #25
0
 function reader_excel($destination, $phonebook_id)
 {
     // Set output Encoding.
     $data = new Spreadsheet_Excel_Reader();
     $data->setOutputEncoding('utf-8');
     //”data.xls”是指要导入到mysql中的excel文件
     $data->read($destination);
     echo $phonebook_id;
     echo '<br/>';
     echo "<table style='border-collapse:collapse;border-spacing:0;border:1px solid #000'>";
     for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
         //以下注释的for循环打印excel表数据
         $array = array();
         $contacts_arr = array();
         echo "<tr  style='border:1px solid #000'>";
         for ($j = 1; $j <= 3; $j++) {
             if (empty($data->sheets[0]['cells'][$i][$j])) {
                 $array[$j - 1] = null;
                 echo "<td style='border:1px solid #000'></td>";
             } else {
                 $array[$j - 1] = $data->sheets[0]['cells'][$i][$j];
                 echo "<td style='border:1px solid #000'>" . $data->sheets[0]['cells'][$i][$j] . "</td>";
             }
         }
         echo '</tr>';
         var_dump($array);
         echo '<br/>';
         $sql_fetchlongnum = "SELECT * FROM contacts where longnum ='{$array[1]}'";
         $old_phonebook_id = fetchOne($sql_fetchlongnum)['phonebook_id'];
         if ($old_phonebook_id) {
             $new_phonebook_id = $old_phonebook_id . '|' . $phonebook_id;
             $contacts_arr = array('phonebook_id' => $new_phonebook_id);
             update('contacts', $contacts_arr, "longnum=" . "'{$array['1']}'");
         } else {
             $contacts_arr = array('phonebook_id' => $phonebook_id, 'name' => $array[0], 'longnum' => $array[1], 'shortnum' => $array[2]);
             echo insert('contacts', $contacts_arr);
         }
     }
     echo "</table>";
 }
 function TestBackupExcel()
 {
     $filename = 'products_test.xls';
     $this->p_ex->DownloadIdMot = 1;
     // We will create file with articles, that are connected with id_mot=1
     $this->p_ex->DownloadRubriques = array(1);
     // We will create file with articles, that lie in rubrique 1
     $this->p_ex->BackupExcel($filename);
     $full_path = $this->p_ex->GetTmpDir() . $filename;
     $this->assertTrue(file_exists($full_path), 'Excel file hasn\'t been created!');
     $reader = new Spreadsheet_Excel_Reader();
     $reader->setUTFEncoder('iconv');
     $reader->setOutputEncoding('UTF-8');
     $reader->read($full_path);
     $this->assertEqual(1, count($reader->sheets));
     // Document must contain 1 sheet
     $rows = $reader->sheets[0]["cells"];
     $this->assertEqual(3, count($rows));
     // Document must contain 1 heading + 1 data = 2 rows
     if (file_exists($full_path)) {
         unlink($full_path);
     }
 }
Beispiel #27
0
 function uploadScore($exam_paper)
 {
     $this->exam->id = $exam_paper;
     if ($this->input->post('submit')) {
         try {
             if ($_FILES['score_table']['error'] > 0) {
                 throw new Exception('文件上错错误:错误代码: ' . $_FILES['score_table']['error']);
             }
             if (!(preg_match('/\\.(\\w*?)$/', $_FILES['score']['name'], $extname_match) && $extname_match[1] == 'xls')) {
                 throw new Exception('文件格式错误,请上传xls格式的excel表格');
             }
             require APPPATH . 'third_party/PHP-ExcelReader/reader.php';
             $data = new Spreadsheet_Excel_Reader();
             $data->setOutputEncoding('utf-8');
             $data->setRowColOffset(0);
             $data->read($_FILES['score']['tmp_name']);
             $this->exam->uploadScore($data);
         } catch (Exception $e) {
             $this->output->message($e->getMessage(), 'warning');
         }
     }
     $this->load->view('exam/uploadscore');
 }
function rsvp_admin_import()
{
    global $wpdb;
    if (count($_FILES) > 0) {
        check_admin_referer('rsvp-import');
        require_once "Excel/reader.php";
        $data = new Spreadsheet_Excel_Reader();
        $data->read($_FILES['importFile']['tmp_name']);
        $skipFirstRow = false;
        if ($data->sheets[0]['numCols'] >= 6) {
            // Associating private questions... have to skip the first row
            $skipFirstRow = true;
        }
        if ($data->sheets[0]['numCols'] >= 2) {
            $count = 0;
            $i = $skipFirstRow ? 2 : 1;
            for ($i; $i <= $data->sheets[0]['numRows']; $i++) {
                $fName = trim($data->sheets[0]['cells'][$i][1]);
                $fName = mb_convert_encoding($fName, 'UTF-8', mb_detect_encoding($fName, 'UTF-8, ISO-8859-1', true));
                $lName = trim($data->sheets[0]['cells'][$i][2]);
                $lName = mb_convert_encoding($lName, 'UTF-8', mb_detect_encoding($lName, 'UTF-8, ISO-8859-1', true));
                $email = trim($data->sheets[0]['cells'][$i][3]);
                $personalGreeting = isset($data->sheets[0]['cells'][$i][5]) ? $personalGreeting = $data->sheets[0]['cells'][$i][5] : "";
                $passcode = isset($data->sheets[0]['cells'][$i][6]) ? $data->sheets[0]['cells'][$i][6] : "";
                if (rsvp_require_unique_passcode() && !rsvp_is_passcode_unique($passcode, 0)) {
                    $passcode = rsvp_generate_passcode();
                }
                if (!empty($fName) && !empty($lName)) {
                    $sql = "SELECT id FROM " . ATTENDEES_TABLE . " \n\t\t\t\t\t\t \tWHERE firstName = %s AND lastName = %s ";
                    $res = $wpdb->get_results($wpdb->prepare($sql, $fName, $lName));
                    if (count($res) == 0) {
                        $wpdb->insert(ATTENDEES_TABLE, array("firstName" => $fName, "lastName" => $lName, "email" => $email, "personalGreeting" => $personalGreeting, "passcode" => $passcode), array('%s', '%s', '%s', '%s'));
                        $count++;
                    }
                }
            }
            if ($data->sheets[0]['numCols'] >= 4) {
                // There must be associated users so let's associate them
                $i = $skipFirstRow ? 2 : 1;
                for ($i; $i <= $data->sheets[0]['numRows']; $i++) {
                    $fName = trim($data->sheets[0]['cells'][$i][1]);
                    $lName = trim($data->sheets[0]['cells'][$i][2]);
                    if (!empty($fName) && !empty($lName) && count($data->sheets[0]['cells'][$i]) >= 3) {
                        // Get the user's id
                        $sql = "SELECT id FROM " . ATTENDEES_TABLE . " \n\t\t\t\t\t\t\t \tWHERE firstName = %s AND lastName = %s ";
                        $res = $wpdb->get_results($wpdb->prepare($sql, $fName, $lName));
                        if (count($res) > 0 && isset($data->sheets[0]['cells'][$i][4])) {
                            $userId = $res[0]->id;
                            // Deal with the assocaited users...
                            $associatedUsers = explode(",", trim($data->sheets[0]['cells'][$i][4]));
                            if (is_array($associatedUsers)) {
                                foreach ($associatedUsers as $au) {
                                    $user = explode(" ", trim($au), 2);
                                    // Three cases, they didn't enter in all of the information, user exists or doesn't.
                                    // If user exists associate the two users
                                    // If user does not exist add the user and then associate the two
                                    if (is_array($user) && count($user) == 2) {
                                        $sql = "SELECT id FROM " . ATTENDEES_TABLE . " \n\t\t\t\t\t\t\t\t\t\t\t \tWHERE firstName = %s AND lastName = %s ";
                                        $userRes = $wpdb->get_results($wpdb->prepare($sql, trim($user[0]), trim($user[1])));
                                        if (count($userRes) > 0) {
                                            $newUserId = $userRes[0]->id;
                                        } else {
                                            // Insert them and then we can associate them...
                                            $wpdb->insert(ATTENDEES_TABLE, array("firstName" => trim($user[0]), "lastName" => trim($user[1])), array('%s', '%s'));
                                            $newUserId = $wpdb->insert_id;
                                            $count++;
                                        }
                                        $wpdb->insert(ASSOCIATED_ATTENDEES_TABLE, array("attendeeID" => $newUserId, "associatedAttendeeID" => $userId), array("%d", "%d"));
                                        $wpdb->insert(ASSOCIATED_ATTENDEES_TABLE, array("attendeeID" => $userId, "associatedAttendeeID" => $newUserId), array("%d", "%d"));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // if($data->sheets[0]['numCols'] >= 3)...
            if ($data->sheets[0]['numCols'] >= 6) {
                $private_questions = array();
                for ($qid = 6; $qid <= $data->sheets[0]['numCols']; $qid++) {
                    $pqid = str_replace("pq_", "", $data->sheets[0]['cells'][1][$qid]);
                    if (is_numeric($pqid)) {
                        $private_questions[$qid] = $pqid;
                    }
                }
                if (count($private_questions) > 0) {
                    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
                        $fName = trim($data->sheets[0]['cells'][$i][1]);
                        $lName = trim($data->sheets[0]['cells'][$i][2]);
                        if (!empty($fName) && !empty($lName)) {
                            // Get the user's id
                            $sql = "SELECT id FROM " . ATTENDEES_TABLE . " \n  \t\t\t\t\t\t\t \tWHERE firstName = %s AND lastName = %s ";
                            $res = $wpdb->get_results($wpdb->prepare($sql, $fName, $lName));
                            if (count($res) > 0) {
                                $userId = $res[0]->id;
                                foreach ($private_questions as $key => $val) {
                                    if (strToUpper($data->sheets[0]['cells'][$i][$key]) == "Y") {
                                        $wpdb->insert(QUESTION_ATTENDEES_TABLE, array("attendeeID" => $userId, "questionID" => $val), array("%d", "%d"));
                                    }
                                }
                            }
                        }
                    }
                }
                // if(count($priv...))
            }
            // if($data->sheets[0]['numCols'] >= 6)....
            ?>
			<p><strong><?php 
            echo $count;
            ?>
</strong> total records were imported.</p>
			<p>Continue to the RSVP <a href="admin.php?page=rsvp-top-level">list</a></p>
			<?php 
        }
    } else {
        ?>
			<form name="rsvp_import" method="post" enctype="multipart/form-data">
				<?php 
        wp_nonce_field('rsvp-import');
        ?>
				<p>Select an excel file (only xls please, xlsx is not supported....yet) in the following format:<br />
				<strong>First Name</strong> | <strong>Last Name</strong> | <strong>Email</strong> | 
        <strong>Associated Attendees*</strong> | <strong>Custom Message</strong> | <strong>Passcode</strong> | <strong>Private Question Association**</strong>
				</p>
				<p>
				* associated attendees should be separated by a comma it is assumed that the first space encountered will separate the first and last name.
				</p>
        <p>
          ** This can be multiple columns each column is associated with one of the following private questions. If you wish 
          to have the guest associated with the question put a &quot;Y&quot; in the column otherwise put whatever else you want. The header name will be the &quot;private import key&quot; which is also listed below. It has the format of pq_* where * is a number.  
          <ul>
          <?php 
        $questions = $wpdb->get_results("SELECT id, question FROM " . QUESTIONS_TABLE . " WHERE permissionLevel = 'private'");
        foreach ($questions as $q) {
            ?>
            <li><?php 
            echo htmlspecialchars(stripslashes($q->question));
            ?>
 - pq_<?php 
            echo $q->id;
            ?>
</li>
          <?php 
        }
        ?>
          </ul>
        </p>
				<p>A header row is not expected, UNLESS you are associating private questions.</p>
				<p><input type="file" name="importFile" id="importFile" /></p>
				<p><input type="submit" value="Import File" name="goRsvp" /></p>
			</form>
		<?php 
    }
}
Beispiel #29
0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Untitled Document</title>
</head>
<body>
	<?php 
error_reporting(E_ALL ^ E_NOTICE);
require_once 'Excel/reader.php';
// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();
// Set output Encoding.
$data->setOutputEncoding('utf-8');
//$data->read($filepath.$filename);
//$data->read("test1.xls");
$data->read($file_path);
$list_result = $data->sheets[0]['cells'];
//导入的excel表格的第一个shell数据结果
?>

</body>
</html>
Beispiel #30
0
/**
 * Handles a given Excel spreadsheets as in the template provided
 */
function lp_upload_quiz_action_handling()
{
    global $debug;
    $_course = api_get_course_info();
    $courseId = $_course['real_id'];
    if (!isset($_POST['submit_upload_quiz'])) {
        return;
    }
    // Get the extension of the document.
    $path_info = pathinfo($_FILES['user_upload_quiz']['name']);
    // Check if the document is an Excel document
    if ($path_info['extension'] != 'xls') {
        return;
    }
    // Read the Excel document
    $data = new Spreadsheet_Excel_Reader();
    // Set output Encoding.
    $data->setOutputEncoding(api_get_system_encoding());
    // Reading the xls document.
    $data->read($_FILES['user_upload_quiz']['tmp_name']);
    $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null;
    $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null;
    $useCustomScore = isset($_POST['user_custom_score']) ? true : false;
    $propagateNegative = 0;
    if ($useCustomScore && !empty($incorrectScore)) {
        if ($incorrectScore < 0) {
            $propagateNegative = 1;
        }
    }
    // Variables
    $quiz_index = 0;
    $question_title_index = array();
    $question_name_index_init = array();
    $question_name_index_end = array();
    $score_index = array();
    $feedback_true_index = array();
    $feedback_false_index = array();
    $number_questions = 0;
    $question_description_index = array();
    // Reading all the first column items sequentially to create breakpoints
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if ($data->sheets[0]['cells'][$i][1] == 'Quiz' && $i == 1) {
            $quiz_index = $i;
            // Quiz title position, only occurs once
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Question') {
            $question_title_index[] = $i;
            // Question title position line
            $question_name_index_init[] = $i + 1;
            // Questions name 1st position line
            $number_questions++;
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Score') {
            $question_name_index_end[] = $i - 1;
            // Question name position
            $score_index[] = $i;
            // Question score position
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackTrue') {
            $feedback_true_index[] = $i;
            // FeedbackTrue position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackFalse') {
            $feedback_false_index[] = $i;
            // FeedbackFalse position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'EnrichQuestion') {
            $question_description_index[] = $i;
        }
    }
    // Variables
    $quiz = array();
    $question = array();
    $new_answer = array();
    $score_list = array();
    $feedback_true_list = array();
    $feedback_false_list = array();
    $question_description = array();
    // Getting questions.
    $k = $z = $q = $l = $m = 0;
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if (is_array($data->sheets[0]['cells'][$i])) {
            $column_data = $data->sheets[0]['cells'][$i];
            // Fill all column with data to have a full array
            for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                if (empty($column_data[$x])) {
                    $data->sheets[0]['cells'][$i][$x] = '';
                }
            }
            // Array filled with data
            $column_data = $data->sheets[0]['cells'][$i];
        } else {
            $column_data = '';
        }
        // Fill quiz data
        if ($quiz_index == $i) {
            // The title always in the first position
            $quiz = $column_data;
        } elseif (in_array($i, $question_title_index)) {
            //a complete line where 1st column is 'Question'
            $question[$k] = $column_data;
            $k++;
        } elseif (in_array($i, $score_index)) {
            //a complete line where 1st column is 'Score'
            $score_list[$z] = $column_data;
            $z++;
        } elseif (in_array($i, $feedback_true_index)) {
            //a complete line where 1st column is 'FeedbackTrue'
            $feedback_true_list[$q] = $column_data;
            $q++;
        } elseif (in_array($i, $feedback_false_index)) {
            //a complete line where 1st column is 'FeedbackFalse' for wrong answers
            $feedback_false_list[$l] = $column_data;
            $l++;
        } elseif (in_array($i, $question_description_index)) {
            //a complete line where 1st column is 'EnrichQuestion'
            $question_description[$m] = $column_data;
            $m++;
        }
    }
    // Get answers
    for ($i = 0; $i < count($question_name_index_init); $i++) {
        for ($j = $question_name_index_init[$i]; $j <= $question_name_index_end[$i]; $j++) {
            if (is_array($data->sheets[0]['cells'][$j])) {
                $column_data = $data->sheets[0]['cells'][$j];
                // Fill all column with data
                for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                    if (empty($column_data[$x])) {
                        $data->sheets[0]['cells'][$j][$x] = '';
                    }
                }
                $column_data = $data->sheets[0]['cells'][$j];
                // Array filled of data
                if (is_array($data->sheets[0]['cells'][$j]) && count($data->sheets[0]['cells'][$j]) > 0) {
                    $new_answer[$i][$j] = $data->sheets[0]['cells'][$j];
                }
            }
        }
    }
    // Quiz title.
    $quiz_title = $quiz[2];
    if ($quiz_title != '') {
        // Variables
        $type = 2;
        $random = $active = $results = $max_attempt = $expired_time = 0;
        // Make sure feedback is enabled (3 to disable), otherwise the fields
        // added to the XLS are not shown, which is confusing
        $feedback = 0;
        // Quiz object
        $exercise = new Exercise();
        //
        $quiz_id = $exercise->createExercise($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback, $propagateNegative);
        if ($quiz_id) {
            // insert into the item_property table
            api_item_property_update($_course, TOOL_QUIZ, $quiz_id, 'QuizAdded', api_get_user_id());
            // Import questions.
            for ($i = 0; $i < $number_questions; $i++) {
                // Question name
                $question_title = $question[$i][2];
                $question_description_text = "<p></p>";
                if (isset($question_description[$i][2])) {
                    // Question description.
                    $question_description_text = "<p>" . $question_description[$i][2] . "</p>";
                }
                // Unique answers are the only question types available for now
                // through xls-format import
                $question_id = null;
                $detectQuestionType = detectQuestionType($new_answer[$i], $score_list);
                /** @var Question $answer */
                switch ($detectQuestionType) {
                    case FREE_ANSWER:
                        $answer = new FreeAnswer();
                        break;
                    case GLOBAL_MULTIPLE_ANSWER:
                        $answer = new GlobalMultipleAnswer();
                        break;
                    case MULTIPLE_ANSWER:
                        $answer = new MultipleAnswer();
                        break;
                    case UNIQUE_ANSWER:
                    default:
                        $answer = new UniqueAnswer();
                        break;
                }
                if ($question_title != '') {
                    $question_id = $answer->create_question($quiz_id, $question_title, $question_description_text, 0, $answer->type);
                }
                $total = 0;
                if (is_array($new_answer[$i]) && !empty($question_id)) {
                    $id = 1;
                    $answers_data = $new_answer[$i];
                    $globalScore = null;
                    $objAnswer = new Answer($question_id, $courseId);
                    $globalScore = $score_list[$i][3];
                    // Calculate the number of correct answers to divide the
                    // score between them when importing from CSV
                    $numberRightAnswers = 0;
                    foreach ($answers_data as $answer_data) {
                        if (strtolower($answer_data[3]) == 'x') {
                            $numberRightAnswers++;
                        }
                    }
                    foreach ($answers_data as $answer_data) {
                        $answerValue = $answer_data[2];
                        $correct = 0;
                        $score = 0;
                        if (strtolower($answer_data[3]) == 'x') {
                            $correct = 1;
                            $score = $score_list[$i][3];
                            $comment = $feedback_true_list[$i][2];
                        } else {
                            $comment = $feedback_false_list[$i][2];
                            $floatVal = (double) $answer_data[3];
                            if (is_numeric($floatVal)) {
                                $score = $answer_data[3];
                            }
                        }
                        if ($useCustomScore) {
                            if ($correct) {
                                $score = $correctScore;
                            } else {
                                $score = $incorrectScore;
                            }
                        }
                        // Fixing scores:
                        switch ($detectQuestionType) {
                            case GLOBAL_MULTIPLE_ANSWER:
                                $score /= $numberRightAnswers;
                                break;
                            case UNIQUE_ANSWER:
                                break;
                            case MULTIPLE_ANSWER:
                                if (!$correct) {
                                    //$total = $total - $score;
                                }
                                break;
                        }
                        $objAnswer->createAnswer($answerValue, $correct, $comment, $score, $id);
                        $total += $score;
                        $id++;
                    }
                    $objAnswer->save();
                    $questionObj = Question::read($question_id, $courseId);
                    switch ($detectQuestionType) {
                        case GLOBAL_MULTIPLE_ANSWER:
                            $questionObj->updateWeighting($globalScore);
                            break;
                        case UNIQUE_ANSWER:
                        case MULTIPLE_ANSWER:
                        default:
                            $questionObj->updateWeighting($total);
                            break;
                    }
                    $questionObj->save();
                } else {
                    if ($detectQuestionType === FREE_ANSWER) {
                        $questionObj = Question::read($question_id, $courseId);
                        $globalScore = $score_list[$i][3];
                        $questionObj->updateWeighting($globalScore);
                        $questionObj->save();
                    }
                }
            }
        }
        if (isset($_SESSION['lpobject'])) {
            if ($debug > 0) {
                error_log('New LP - SESSION[lpobject] is defined', 0);
            }
            $oLP = unserialize($_SESSION['lpobject']);
            if (is_object($oLP)) {
                if ($debug > 0) {
                    error_log('New LP - oLP is object', 0);
                }
                if (empty($oLP->cc) or $oLP->cc != api_get_course_id()) {
                    if ($debug > 0) {
                        error_log('New LP - Course has changed, discard lp object', 0);
                    }
                    $oLP = null;
                    Session::erase('oLP');
                    Session::erase('lpobject');
                } else {
                    $_SESSION['oLP'] = $oLP;
                }
            }
        }
        if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
            $previous = $_SESSION['oLP']->select_previous_item_id();
            $parent = 0;
            // Add a Quiz as Lp Item
            $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quiz_title, '');
            // Redirect to home page for add more content
            header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id']));
            exit;
        } else {
            //  header('location: exercise.php?' . api_get_cidreq());
            echo '<script>window.location.href = "' . api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidReq() . '&exerciseId=' . $quiz_id . '&session_id=' . api_get_session_id() . '"</script>';
        }
    }
}