Skip to content

Instantly share code, notes, and snippets.

@bvelastegui
Last active March 3, 2017 17:57
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 bvelastegui/0baf3e71680f546818114b1773eeb58e to your computer and use it in GitHub Desktop.
Save bvelastegui/0baf3e71680f546818114b1773eeb58e to your computer and use it in GitHub Desktop.
Helper de PHPExcel
<?php
class Excel
{
/** @var PHPExcel */
protected $PHPExcel;
/** @var string */
protected $title;
/** @var int */
protected $sheets = 0;
/**
* Helper para PHPExcel
*
* @see PHPExcel
* @param string $name Nombre del documento
*/
public function __construct($name = 'excel-file')
{
$this->PHPExcel = new PHPExcel();
$this->PHPExcel->getProperties()->setTitle($name);
$this->title = $name;
}
/**
* @return PHPExcel_DocumentProperties
*/
public function getPropiedades()
{
return $this->PHPExcel->getProperties();
}
/**
* Crea una instancia de PHPExcel_Worksheet asignando
* el nombre de la variable $name
*
* @param string $name Nombre del espacio de trabajo
* @param mixed $callback Función anónima
* @return mixed
*/
public function sheet($name, $callback = null)
{
if ($this->sheets === 0)
{
$sheet = $this->PHPExcel->getActiveSheet();
$this->sheets++;
}
else
{
$sheet = $this->PHPExcel->createSheet($this->sheets);
$this->sheets++;
}
$sheet->setTitle($name);
if (!is_null($callback))
{
call_user_func($callback, $sheet);
}
return $sheet;
}
/**
* Exporta el contenido a HTML
*/
public function show()
{
$writer = new PHPExcel_Writer_HTML($this->PHPExcel);
$writer->writeAllSheets();
$writer->save('php://output');
}
/**
* Permite descargar el archivo en 2 formatos
* <ul>
* <li>"xls" Compatible con excel 2003</li>
* <li>"xlsx" Compatible con excel 2007 o superior</li>
* <li>Por defecto exporta el archivo con la extension "xlsx"</li>
* @param string $ext extension del archivo a descargar
*/
public function download($ext = 'xlsx')
{
switch ($ext)
{
case 'xls':
header("Content-Type: application/vnd.ms-excel");
header('Content-Disposition: attachment;filename="' . $this->getTitle() . '.xls"');
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
$writer = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel5');
$writer->save('php://output');
break;
case 'xlsx':
default:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $this->getTitle() . '.xlsx"');
$writer = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
$writer->save('php://output');
break;
}
}
/**
* @return string Titulo del documento
*/
public function getTitle()
{
return $this->title;
}
}

PHPExcel helper

Este helper se diseño con la unica intención de facilitar el uso de PHPExcel

Veamos uno ejemplos de como usuarlo.

1. Agregamos a nuestro autoload

Es importante recordar que require de PHPExcel, si no lo tenemos instalado podemos tipear en nuestra consola

composer require PHPOffice/PHPExcel

Editamos nuestro archivo composer.json y agregamos la sección de autoload con las siguientes lineas:

{
  "autoload": {
    "files" : [
      "helpers/Excel.php"
    ]
  }
}

Ahora tipeamos en nuestra consola

composer dump-autoload

2. Creamos una instancia de la clase

Ya en el código:

<?php
//importamos el autoload de composer
require "vendor/autoload.php";
//creamos una instancia de la clase Excel, 
//asignando un nombre al documento que vamos a generar
$excel = new Excel('NombreArchivo');

3. Trabajar con los Worksheets

Se admiten varias formas de crear Worksheets

3.1 Tradicional

La forma tradicional solo implica llamar al método sheet de la clase Excel ya que este retorna un objeto de tipo PHPExcel_worksheet

$sheet = $excel->sheet('Worksheet 1');
$sheet->setCellValue('A1', 'Tradicional');
$sheet->setCellValue('B1', 'Detalle');
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);

3.2 Invocar una función

Podemos invocar una función declarada

//$sheet es un objeto de tipo PHPExcel_Worksheet
$sheet = $excel->sheet('Worksheet 2','sheet2');

function sheet2(PHPExcel_Worksheet $sheet)
{
	$sheet->setCellValue('A1', 'Invocar');
	$sheet->setCellValue('B1', 'Funciones');
}

3.3 Invocar la función de una clase

//$sheet es un objeto de tipo PHPExcel_Worksheet
$sheet = $excel->sheet('Worksheet 3', array('test', 'sheet3'));

class test
{
  public function sheet3(PHPExcel_Worksheet $sheet)
  {
    $sheet->setCellValue('A1', 'N Orden caso 2');
    $sheet->setCellValue('B1', 'Cliente O.S caso 2');
    $sheet->getColumnDimension('A')->setAutoSize(true);
    $sheet->getColumnDimension('B')->setAutoSize(true);
	}
}

3.4 Usar funciones anónimas

$sheet = $excel->sheet('Worksheet 4', function (PHPExcel_Worksheet $sheet)
{
	$sheet->setCellValue('A1', 'Funciones');
	$sheet->setCellValue('B1', 'Anónimas');
	$sheet->getColumnDimension('A')->setAutoSize(true);
	$sheet->getColumnDimension('B')->setAutoSize(true);
});

4. Descargar o mostrar

Podemos descargar el archivo en 2 formatos:

  • xls Compatible con Excel 2003 en adelante
$excel->download('xls');
  • xlsx Compatible con Excel 2007 en adelante (Extensión usada por defecto)
//$excel->download('xlsx');
$excel->download();

También podemos mostrar en html

$excel->show();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment