-
-
Save bajramemini/9336972 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
//Assuming you have autoloaded everything via PSR-0 or whatever | |
$excel = new Excel('path/to/file.xls'); | |
var_dump($excel->toArray()); |
This file contains hidden or 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 | |
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