-
Notifications
You must be signed in to change notification settings - Fork 24
/
toba_vista_excel.php
378 lines (351 loc) · 11.8 KB
/
toba_vista_excel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
/**
* Genera un pdf a través de una api básica
* @package SalidaGrafica
* @todo La numeración de páginas no funcionará si se cambia la orientación de la misma. Habría que
* implementar un método que en base al tipo de papel y orientación de la página, devuelva las
* coordenadas para una correcta visualización de la numeración de páginas.
* @todo El método insertar_imagen esta implementado con un método en estado beta de la api ezpdf. Usar
* con discreción.
*/
class toba_vista_excel
{
/**
* @var PHPExcel
*/
protected $excel;
protected $objetos = array();
protected $tipo_salida = 'application/vnd.ms-excel';
protected $nombre_archivo = 'salida.xlsx';
protected $tipo_descarga = 'attachment';
protected $writer = 'Xlsx';
protected $cursor_base = array(1,1);
protected $cursor = array(1,1);
protected $temp_salida;
const FORMAT_CURRENCY_USD_CUSTOM = '#,##0.00_- [$USD]';
const FORMAT_DATE_DATETIMEFULL = 'd/m/yy h:mm';
function __construct()
{
$this->excel = new Spreadsheet();
$this->inicializar();
}
function inicializar()
{
}
/**
* @ignore
*/
function asignar_objetos( $objetos )
{
$this->objetos = $objetos;
}
//------------------------------------------------------------------------
//-- Configuracion
//------------------------------------------------------------------------
/**
* Cambia el formato de salida del excel
* @param string $tipo es Excel5, CSV, Excel2007, HTML o Serialized, por defecto es Excel2007 (Office Open XML)
*/
function set_tipo_salida($tipo)
{
$this->writer = $tipo;
}
/**
* Cambia el nombre del archivo que el usuario visualiza al descargar
* @param string $nombre
*/
function set_nombre_archivo($nombre)
{
$this->nombre_archivo = $nombre;
}
/**
* Permite setear el tipo de descarga pdf desde el browser, inline o attachment
* @param string $tipo inline o attachment
*/
function set_tipo_descarga( $tipo )
{
$this->tipo_descarga = $tipo;
}
//------------------------------------------------------------------------
//-- Generacion del excel
//------------------------------------------------------------------------
/**
* @ignore
*/
function generar_salida()
{
if (isset($this->objetos) && is_countable($this->objetos)) {
foreach( $this->objetos as $objeto ) {
$objeto->vista_excel( $this );
}
}
$this->crear_excel();
}
/**
* Retorna el objeto PHPExcel
* @return PHPExcel
*/
function get_excel()
{
return $this->excel;
}
function enviar_archivo()
{
$longitud = filesize($this->temp_salida);
if (file_exists($this->temp_salida)) {
$fp = fopen($this->temp_salida, 'r');
$this->cabecera_http($longitud);
fpassthru($fp);
fclose($fp);
unlink($this->temp_salida);
}
}
protected function crear_excel()
{
$clase = '\PhpOffice\PhpSpreadsheet\Writer' . '\\'. $this->writer;
$writer = new $clase($this->excel);
$this->temp_salida = toba::proyecto()->get_path_temp().'/'.uniqid();
$writer->save($this->temp_salida);
}
protected function cabecera_http($longitud)
{
toba_http::headers_download($this->tipo_salida, $this->nombre_archivo, $longitud, $this->tipo_descarga);
}
//------------------------------------------------------------------------
//-- API de Creación
//------------------------------------------------------------------------
function crear_hoja($nombre=null)
{
$hoja = $this->excel->createSheet();
if (isset($nombre)) {
$this->check_caracteres($nombre);
$hoja->setTitle(utf8_encode(strval($nombre)));
}
$this->excel->setActiveSheetIndex($this->excel->getSheetCount()-1);
$this->cursor = $this->cursor_base;
}
function set_hoja_nombre($nombre)
{
if (strlen($nombre) > 31) {
$nombre = substr($nombre, 0, 30);
$this->check_caracteres($nombre);
}
$this->excel->getActiveSheet()->setTitle(utf8_encode(strval($nombre)));
}
function get_hoja_nombre()
{
return $this->excel->getActiveSheet()->getTitle();
}
/**
* Cambia el cursor de inserción en el flujo del excel generado
* @param int $columna Número de columna, base 0
* @param int $fila, Número de fila, base 1
*/
function set_cursor($columna, $fila)
{
$this->cursor = array($columna, $fila);
}
function get_cursor()
{
return $this->cursor;
}
/**
*
* @param array $datos
* @param array $titulos
* @param array opciones => array(
* 'columna' =>
* 'ancho' => (auto|numero)
* 'estilo' => array(
* 'font' => array('name' => 'Arial', 'bold' => true, 'italic' => false, 'underline' => Font::UNDERLINE_DOUBLE, 'strike' => false, 'color' => array('argb' => 'FF808080')),
* 'borders' => array(
* 'bottom' => array('style' => Border::BORDER_DASHDOT,'color' => array('argb' => 'FF808080')),
* 'top' => array( 'style' =>Border::BORDER_DASHDOT, 'color' => array('argb' => 'FF808080'))
* )
* )
* )
* @param array $origen Arreglo [columna,fila], sino se toma el cursor actual
*
*/
function tabla($datos, $titulos=array(), $opciones=array(), $totales=array(), $origen=null)
{
//Determina la agrupacion
$agrupacion = array();
foreach ($opciones as $clave => $atributos) {
if (isset($atributos['grupo']) && $atributos['grupo'] != '') {
$agrupacion[$atributos['grupo']][] = $clave;
}
}
if (! isset($origen)) {
$origen = $this->cursor;
//Determina donde va a terminar la tabla
$this->cursor[1] += count($datos);
if (! empty($titulos)) {
$this->cursor[1]++;
}
if (! empty($totales)) {
$this->cursor[1]++;
}
if (! empty($agrupacion)) {
$this->cursor[1]++;
}
}
if (! empty($agrupacion)) {
$origen[1]++; //Tiene que entrar una fila más
}
$borde = array('borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN );
$estilo_titulos = array(
'font' => array('bold' => true),
'borders' => array('bottom' => $borde, 'top' => $borde, 'left' => $borde, 'right' => $borde),
'fill' => array(
'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID ,
'rotation' => 0,
'startColor' => array('argb' => 'FFE6E6E6'),
),
);
$hoja = $this->excel->getActiveSheet();
//--- Titulos
if (! empty($titulos)) {
$x=0;
$ultimo_grupo = '';
foreach($titulos as $clave => $valor) {
$inicio = $origen[0] + $x; //Desplazado X columnas a derecha horizontalmente
//-- Pone el titulo de la columna
if (isset($valor) || !isset($opciones[$clave]['borrar_estilos_nulos'])) {
$hoja->setCellValueByColumnAndRow($inicio, $origen[1],utf8_encode(strval($valor)));
$hoja->getStyleByColumnAndRow($inicio, $origen[1])->applyFromArray($estilo_titulos);
}
//-- Maneja la agrupacion
if (! empty($agrupacion)) {
if (isset($opciones[$clave]['grupo']) && $opciones[$clave]['grupo'] != '') {
$grupo_actual = $opciones[$clave]['grupo'];
} else {
$grupo_actual = '';
}
$hoja->setCellValueByColumnAndRow($inicio, $origen[1]-1, utf8_encode(strval($grupo_actual)));
$hoja->getStyleByColumnAndRow($inicio, $origen[1]-1)->applyFromArray($estilo_titulos);
if ($ultimo_grupo != $grupo_actual) {
if (isset($agrupacion[$grupo_actual]) && count($agrupacion[$grupo_actual]) > 1) {
//Hay que mergear horizontalmente, segun la cantidad de columnas en el grupo
$fin = $inicio + (count($agrupacion[$grupo_actual]) - 1);
$hoja->mergeCellsByColumnAndRow($inicio, $origen[1]-1, $fin, $origen[1]-1);
}
}
if ($grupo_actual == '') {
//El grupo es vacio o no tiene grupo, hay que mergear verticalmente esta unica fila
$hoja->setCellValueByColumnAndRow($inicio, $origen[1]-1, utf8_encode(strval($valor)));
$hoja->mergeCellsByColumnAndRow($inicio, $origen[1]-1, $inicio, $origen[1]);
}
$ultimo_grupo = $grupo_actual;
}
$x++;
}
$origen[1]++;
}
//--- Datos
$columnas = array();
$y = 0;
$x = 0;
foreach($datos as $filas) {
$x = 0;
foreach($filas as $clave => $valor) {
$columnas[$clave] = $x +1; //El indice arranca en base 1..no puedo mapear mal la columna
$hoja->setCellValueByColumnAndRow($origen[0] + $x, $origen[1] + $y, utf8_encode(strval($valor)));
if (! isset($opciones[$clave]['estilo']['borders'])) {
$opciones[$clave]['estilo']['borders']= array('bottom' => $borde, 'top' => $borde, 'left' => $borde, 'right' => $borde);
}
//--- Se borran los estilos si no tiene valor (opcional)
if (!isset($valor) && isset($opciones[$clave]['borrar_estilos_nulos'])) {
$opciones[$clave]['estilo'] = array();
}
$hoja->getStyleByColumnAndRow($origen[0] + $x, $origen[1] + $y)->applyFromArray($opciones[$clave]['estilo']);
if (isset($opciones[$clave]['ancho'])) {
if ($opciones[$clave]['ancho'] == 'auto') {
$hoja->getColumnDimensionByColumn($origen[0] + $x)->setAutoSize(true);
} else {
$hoja->getColumnDimensionByColumn($origen[0] + $x)->setWidth($opciones[$clave]['ancho']);
}
}
$x++;
}
$y++;
}
//--- Totales
foreach($totales as $clave) {
$col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnas[$clave]);
$desde = $col.(($origen[1]));
$hasta = $col.(($origen[1]+$y)-1);
$total = "=SUM($desde:$hasta)";
$destino_x = $origen[0]+$columnas[$clave] -1; //Quito lo que agregue antes a $columnas[$clave] el origen ya tiene base 1
$destino_y = $origen[1] + $y;
$hoja->setCellValueByColumnAndRow($destino_x, $destino_y, utf8_encode(strval($total)) );
$estilo = $hoja->getStyleByColumnAndRow($destino_x, $destino_y);
unset($opciones[$clave]['estilo']['borders']);
$estilo->applyFromArray($opciones[$clave]['estilo']);
$estilo->getFont()->setBold(true);
$estilo->getBorders()->getBottom()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK );
$estilo->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK );
}
return array($origen, array($origen[0]+($x-1), $origen[1]+($y-1)));
}
function separacion($cant_filas, $cant_columnas=0)
{
$this->cursor[1] += $cant_filas;
$this->cursor[0] += $cant_columnas;
}
function titulo($titulo, $celdas_ancho=1, $origen=null)
{
$estilos = array(
'font' => array('
bold' => true,
'size' => 14,
'color' => array('argb' => \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE)
),
'alignment' => array(
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER
),
'fill' => array(
'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => array('argb' => 'FF808080')
),
'borders' => array(
'allBorders' => array('borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM)
)
);
$altura = 20;
$this->texto($titulo, $estilos, $celdas_ancho, $altura, $origen);
}
function texto($texto, $estilos=array(), $celdas_ancho=1, $altura=null, $origen=null)
{
if (! isset($origen)) {
$origen = $this->cursor;
$this->cursor[1]++;
}
$hoja = $this->excel->getActiveSheet();
$hoja->setCellValueByColumnAndRow($origen[0], $origen[1],utf8_encode(strval($texto)) );
$hoja->setBreak('A1', Worksheet::BREAK_COLUMN );
$estilo = $hoja->getStyleByColumnAndRow($origen[0], $origen[1]);
$estilo->applyFromArray($estilos);
if (isset($altura)) {
$hoja->getRowDimension($origen[1])->setRowHeight($altura);
}
if ($celdas_ancho > 1) {
$fin = ($origen[0] + $celdas_ancho) -1;
$hoja->mergeCellsByColumnAndRow($origen[0], $origen[1], $fin, $origen[1]);
for($i=$origen[0]+1; $i<=$fin; $i++) {
$estilo = $hoja->getStyleByColumnAndRow($i, $origen[1]);
$estilo->applyFromArray($estilos);
}
}
}
private function check_caracteres($texto)
{
$ic = Worksheet::getInvalidCharacters();
if (str_replace($ic, '', $texto) !== $texto) {
throw new toba_error('El texto tiene caracteres inválidos para Excel');
}
}
}
?>