public function importExcelToMysql($filePath, $fields = array(), $model = null, $startingRow = 2) { $objPHPExcel = PHPExcel_IOFactory::load($filePath); foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) { //field validation $fieldValidate = array(); $validated = FALSE; for ($col = 0; $col < count($fields); ++$col) { $val = $worksheet->getCellByColumnAndRow($fields[$col]['col'], 1)->getValue(); $fieldValidate[$fields[$col]['name']] = $val; } if ($fieldValidate['code'] == 'Kode Satker' and $fieldValidate['name'] == 'Nama Satker') { $validated = TRUE; } //end of validation if ($validated == TRUE) { $isSuccess = FALSE; $highestRow = $worksheet->getHighestRow(); // e.g. 10 for ($row = $startingRow; $row <= $highestRow; ++$row) { $attributes = array(); for ($col = 0; $col < count($fields); ++$col) { $val = $worksheet->getCellByColumnAndRow($fields[$col]['col'], $row)->getValue(); $attributes[$fields[$col]['name']] = $val; } $code = trim($attributes['code'], " \t\n\r\v"); $recorded = Satker::model()->find(array('condition' => "code='{$code}'")); if ($attributes['code'] != NULL && $attributes['name'] != NULL) { if ($recorded) { $recorded->attributes = $attributes; $recorded->code = $code; if ($recorded->update()) { $isSuccess = TRUE; } } else { $model = new Satker(); $model->attributes = $attributes; $model->code = $code; if ($model->save()) { $isSuccess = TRUE; } } } } if ($isSuccess) { unlink($filePath); Yii::app()->user->setFlash('success', "Data berhasil diimport."); $this->redirect(array('index')); } else { unlink($filePath); Yii::app()->user->setFlash('error', "Mohon isikan data dengan lengkap."); } } else { unlink($filePath); Yii::app()->user->setFlash('error', "Pastikan file yang Anda upload sudah benar!"); $this->redirect(array('importData')); } } }