Using PHPExcel with Yii
I was running into problems with conflicting autoloaders when I tried to use PHPExcel with the Yii framework. There are instructions out on the web on how to resolve this, but they are only useful if you’re not creating instances of Yii active record models while you’re using PHPExcel. That’s fine if you’re using Yii to create an Excel spreadsheet from already instantiated Yii classes, but my need is to read an Excel spreadsheet and import its data into my database.
It turns out that this is fairly straightforward as well. The trick is in realizing that PHPExcel is registering its autoloader when it’s instantiated, so you don’t need to register it yourself.
public function actionImport() { $message = ''; if (!empty($_POST)) { $file = CUploadedFile::getInstanceByName('import'); $spec = Yii::app()->basePath.'/data/imports/'.$file->name; $file->saveAs($spec); spl_autoload_unregister(array('YiiBase','autoload')); require(Yii::app()->basePath.'/extensions/phpexcel/Classes/PHPExcel.php'); spl_autoload_register(array('YiiBase', 'autoload')); try { $inputFileType = PHPExcel_IOFactory::identify($spec); $objReader = PHPExcel_IOFactory::createReader($inputFileType); if ($inputFileType != 'CSV') { $objReader->setReadDataOnly(true); } $objPHPExcel = $objReader->load($spec); $objWorksheet = $objPHPExcel->setActiveSheetIndex(0); $highestRow = $objWorksheet->getHighestRow(); for ($row = 1;$row < $highestRow+1; $row++) { $myObjThing = new MyObject; // Yii AR model $myObjThing->someField = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue(); $myObjThing->otherField = $objWorksheet->getCellByColumnAndRow(5, $row)->getValue(); $myObjThing->save(false); $myObjThing->detachBehaviors(); // PHP < 5.3 memory management unset($myObjThing); } } catch (Exception $e) { $message = 'There was a problem handling your file. Technical details: '.$e->getMessage(); } if (! empty($message)) { Yii::app()->user->setFlash('error',$message); } } $this->render('import'); }
Pretend WordPress didn’t hose the formatting on that …