Created
June 6, 2012 10:47
-
-
Save hugodotlau/2881252 to your computer and use it in GitHub Desktop.
Using PHPExcel with Yii
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
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'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from: http://www.fogbound.net/archives/2011/10/21/using-phpexcel-with-yii/