Skip to content

Instantly share code, notes, and snippets.

@barryvdh
Last active December 4, 2022 23:25
Show Gist options
  • Save barryvdh/7989606 to your computer and use it in GitHub Desktop.
Save barryvdh/7989606 to your computer and use it in GitHub Desktop.
Simple php-excel class to load an Excel file into an array (using Laravel json/array interface, but you don't have to use that). Don't forget to require https://packagist.org/packages/phpoffice/phpexcel or https://packagist.org/packages/codeplex/phpexcel
<?php
//Assuming you have autoloaded everything via PSR-0 or whatever
$excel = new Excel('path/to/file.xls');
var_dump($excel->toArray());
<?php
use Illuminate\Support\Contracts\ArrayableInterface;
use Illuminate\Support\Contracts\JsonableInterface;
class Excel implements ArrayableInterface, JsonableInterface{
protected $objPHPExcel;
public function __construct($file){
if($file instanceof \SplFileInfo){
$filename = $file->getRealPath();
}else{
$filename = $file;
}
$this->objPHPExcel = PHPExcel_IOFactory::load($filename);
$this->objPHPExcel->setActiveSheetIndex(0);
}
public function setActiveSheetIndex($index){
$this->objPHPExcel->setActiveSheetIndex($index);
}
/**
* Create array from worksheet
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param boolean $calculateFormulas Should formulas be calculated?
* @param boolean $formatData Should formatting be applied to cell values?
* @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
* @return array
*/
public function toArray($nullValue = null, $calculateFormulas = true, $formatData = false){
$rows = $this->objPHPExcel->getActiveSheet()->toArray($nullValue,$calculateFormulas,$formatData,false);
$headers = array_shift($rows);
array_walk($rows, function(&$values) use($headers){
$values = array_combine($headers, $values);
});
return $rows;
}
public function toJson($options = 0, $nullValue = null, $calculateFormulas = true, $formatData = false){
return json_encode($this->toArray($nullValue,$calculateFormulas,$formatData), $options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment