Skip to content

Instantly share code, notes, and snippets.

@hugodotlau
Created June 6, 2012 10:47
Show Gist options
  • Save hugodotlau/2881252 to your computer and use it in GitHub Desktop.
Save hugodotlau/2881252 to your computer and use it in GitHub Desktop.
Using PHPExcel with Yii
<?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');
}
@hugodotlau
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment