Skip to content

Instantly share code, notes, and snippets.

@jasondavis
Forked from barryvdh/Excel.php
Created February 21, 2014 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasondavis/9132413 to your computer and use it in GitHub Desktop.
Save jasondavis/9132413 to your computer and use it in GitHub Desktop.
<?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);
}
public function toArray(){
$keys = array();
$items = array();
$worksheet = $this->objPHPExcel->getActiveSheet();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, 1);
$val = $cell->getFormattedValue();
$keys[$col] = trim($val);
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$item = array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$key = $keys[$col];
$item[$key] = $val;
}
$items[] = $item;
}
return $items;
}
public function toJson($options = 0){
return json_encode($this->toArray(), $options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment