PHP - Problemas con clase PHPExcel

 
Vista:

Problemas con clase PHPExcel

Publicado por Juan (54 intervenciones) el 28/05/2015 13:38:12
Hola, tengo un problema con la clase PHPExcel, en mi servidor local XAMPP me funciona a las mil maravillas y no me da ningún problema, pero a la hora de subirlo al servidor cuando descargo el archivo me dice que está corrupto, alguien me puede echar una mano. Gracias!

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
<?php
		// Se manda el archivo al navegador web, con el nombre que se indica (Excel2007)
 
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Descarga_BDDAN.xlsx"');
		header('Cache-Control: max-age=0');
 
session_start();
include '../../conf.php';
    $conexion = new mysqli("$local","$usu","$passw","$bdd");
 
	if (mysqli_connect_errno()) {
    	printf("La conexión con el servidor de base de datos falló: %s\n", mysqli_connect_error());
    	exit();
	}
	$consulta = $_SESSION['consulta'];
	$resultado = $conexion->query($consulta);
	if($resultado->num_rows > 0 ){
 
		date_default_timezone_set('Europe/Madrid');
 
		if (PHP_SAPI == 'cli')
			die('Este archivo solo se puede ver desde un navegador web');
 
		/** Se agrega la libreria PHPExcel */
		require_once '../Classes/PHPExcel.php';
 
		// Se crea el objeto PHPExcel
		$objPHPExcel = new PHPExcel();
 
		// Se asignan las propiedades del libro
		$objPHPExcel->getProperties()->setCreator("Codedrinks") //Autor
							 ->setLastModifiedBy("Codedrinks") //Ultimo usuario que lo modificó
							 ->setTitle("Reporte Excel con PHP y MySQL")
							 ->setSubject("Reporte Excel con PHP y MySQL")
							 ->setDescription("Reporte de consulta")
							 ->setKeywords("reporte consulta")
							 ->setCategory("Reporte excel");
 
		$tituloReporte = "Relación de consulta";
		$titulosColumnas = array('ID', 'NOMBRE', 'DESCRIPCIÓN', 'CATEGORÍA', 'PVP', 'UNIDADES','OFERTA');
 
		$objPHPExcel->setActiveSheetIndex(0)
        		    ->mergeCells('A1:F1');
 
		// Se agregan los titulos del reporte
		$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1',$tituloReporte)
        		    ->setCellValue('A3',  $titulosColumnas[0])
		            ->setCellValue('B3',  $titulosColumnas[1])
        		    ->setCellValue('C3',  $titulosColumnas[2])
            		->setCellValue('D3',  $titulosColumnas[3])
                        ->setCellValue('E3',  $titulosColumnas[4])
                        ->setCellValue('F3',  $titulosColumnas[5])
                        ->setCellValue('G3',  $titulosColumnas[6])
                        ;
 
		//Se agregan los datos de la consulta
		$i = 4;
		while ($fila = $resultado->fetch_array()) {
			$objPHPExcel->setActiveSheetIndex(0)
        		    ->setCellValue('A'.$i,  utf8_encode($fila[0]))
		            ->setCellValue('B'.$i,  utf8_encode($fila[1]))
        		    ->setCellValue('C'.$i,  utf8_encode($fila[2]))
            		    ->setCellValue('D'.$i,  utf8_encode($fila[3]))
                            ->setCellValue('E'.$i,  utf8_encode($fila[4]))
                            ->setCellValue('F'.$i,  utf8_encode($fila[5]))
                            ->setCellValue('G'.$i,  utf8_encode($fila[6]));
					$i++;
		}
 
		$estiloTituloReporte = array(
        	'font' => array(
	        	'name'      => 'Verdana',
    	        'bold'      => true,
        	    'italic'    => false,
                'strike'    => false,
               	'size' =>16,
	            	'color'     => array(
    	            	'rgb' => 'FFFFFF'
        	       	)
            ),
	        'fill' => array(
				'type'	=> PHPExcel_Style_Fill::FILL_SOLID,
				'color'	=> array('argb' => 'FF220835')
			),
            'borders' => array(
               	'allborders' => array(
                	'style' => PHPExcel_Style_Border::BORDER_NONE
               	)
            ),
            'alignment' =>  array(
        			'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        			'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
        			'rotation'   => 0,
        			'wrap'          => TRUE
    		)
        );
 
		$estiloTituloColumnas = array(
            'font' => array(
                'name'      => 'Arial',
                'bold'      => true,
                'color'     => array(
                    'rgb' => 'FFFFFF'
                )
            ),
            'fill' 	=> array(
				'type'		=> PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
				'rotation'   => 90,
        		'startcolor' => array(
            		'rgb' => 'FA5858'
        		),
        		'endcolor'   => array(
            		'argb' => 'FF431a5d'
        		)
			),
            'borders' => array(
            	'top'     => array(
                    'style' => PHPExcel_Style_Border::BORDER_MEDIUM ,
                    'color' => array(
                        'rgb' => '143860'
                    )
                ),
                'bottom'     => array(
                    'style' => PHPExcel_Style_Border::BORDER_MEDIUM ,
                    'color' => array(
                        'rgb' => '143860'
                    )
                )
            ),
			'alignment' =>  array(
        			'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        			'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
        			'wrap'          => TRUE
    		));
 
		$estiloInformacion = new PHPExcel_Style();
		$estiloInformacion->applyFromArray(
			array(
           		'font' => array(
               	'name'      => 'Arial',
               	'color'     => array(
                   	'rgb' => '000000'
               	)
           	),
           	'fill' 	=> array(
				'type'		=> PHPExcel_Style_Fill::FILL_SOLID,
				'color'		=> array('argb' => 'FFFFFF')
			),
           	'borders' => array(
               	'left'     => array(
                   	'style' => PHPExcel_Style_Border::BORDER_THIN ,
	                'color' => array(
    	            	'rgb' => '000000'
                   	)
               	)
           	)
        ));
 
		$objPHPExcel->getActiveSheet()->getStyle('A1:G1')->applyFromArray($estiloTituloReporte);
		$objPHPExcel->getActiveSheet()->getStyle('A3:G3')->applyFromArray($estiloTituloColumnas);
		$objPHPExcel->getActiveSheet()->setSharedStyle($estiloInformacion, "A4:G".($i-1));
 
		for($i = 'A'; $i <= 'G'; $i++){
			$objPHPExcel->setActiveSheetIndex(0)
				->getColumnDimension($i)->setAutoSize(TRUE);
		}
 
		// Se asigna el nombre a la hoja
		$objPHPExcel->getActiveSheet()->setTitle('Descarga');
 
		// Se activa la hoja para que sea la que se muestre cuando el archivo se abre
		$objPHPExcel->setActiveSheetIndex(0);
		// Inmovilizar paneles 
		//$objPHPExcel->getActiveSheet(0)->freezePane('A4');
		$objPHPExcel->getActiveSheet(0)->freezePaneByColumnAndRow(0,4);
 
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                ob_end_clean();
		$objWriter->save('php://output');
		exit;
 
	}
	else{
		print_r('No hay resultados para mostrar');
	}
	?>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Problemas con clase PHPExcel

Publicado por Juan (54 intervenciones) el 28/05/2015 15:30:45
Ya lo he solucionado, el error estaba a la hora de incluir el archivo conf.php que es el que tiene los datos de conexión a la bbdd. Por lo que he puesto los datos de conexión directamente en el archivo php sin incluirlos en el conf.php y me va perfectamente.

Espero que le sirva a alguien.

Un saludo!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de xve
Val: 3.943
Oro
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Problemas con clase PHPExcel

Publicado por xve (6935 intervenciones) el 28/05/2015 20:47:33
Gracias por comentarlo Juan!!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Problemas con clase PHPExcel

Publicado por Pablo Cartes (1 intervención) el 10/09/2018 08:04:41
Me paso lo mismo, xampp funcionaba y en el servidor solo me permitia exportar xls y no xlsx que no me limita el numero de columnas del excel generado

El error estaba en la configuracion de mi php del servidor, faltaba agregar las librerias xml
abrir CPanel
ir a PHP Selector

Deben estar GD, ZIP y XML

En mi caso solo agregue: xmlreader, xmlrpc y xmlwriter



ejemplo simple :
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
<?php
require_once 'librerias/phpexcel/Classes/PHPExcel.php';
 
 
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
//$excel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("Office 2007 XLSX Test Document")
							 ->setSubject("Office 2007 XLSX Test Document")
							 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
							 ->setKeywords("office 2007 openxml php")
							 ->setCategory("Test result file");
 
 
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');
 
// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'aaaaaaaaaa');
 
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
 
 
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
 
 
// Redirect output to a client’s web browser (Excel2007)
 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="proyExcel.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar