PHP - reporte en Excel con PHPExcel desde MsSql muy lento

 
Vista:
sin imagen de perfil
Val: 10
Ha aumentado su posición en 17 puestos en PHP (en relación al último mes)
Gráfica de PHP

reporte en Excel con PHPExcel desde MsSql muy lento

Publicado por Y3rs3Y (7 intervenciones) el 18/09/2017 19:33:59
Estimados, realizo una consulta con condicionales if desde php a SQL SERVER 2008 para generar un excel con PHPEXCEL parece que mi codigo no esta del todo optimizado ya que demora como 40 segundos para generar el EXCEL alguno puede apoyarme con la mejora del codigo:
hago conexion mediante ODBC con MSSQL SERVER 2008 seleccionando el mes y año desde un datapicker y paso los datos al otro php mediante cookiess porque no encontre otra forma de pasar variables de jquey a php:
Index.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
<html lang="es">
	<head>
		<title>Descargar Reportes en Excel de sistema SIGES</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
		<link href="css/estilos.css" rel="stylesheet">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
                <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
                <link rel="stylesheet" href="/resources/demos/style.css">
                <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
                <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <style>
        .ui-datepicker table {
            display: none;
        }
    </style>
    <script>
    $(document).ready(function() {
        //opciones del datepicker por defecto
        $.datepicker.regional['es'] = {
            closeText: 'Cerrar',
            prevText: 'Anterior',
            nextText: 'Siguiente',
            minDate: new Date(2011, 09 - 30, 1),
            currentText: 'Actual',
            monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre', 'Octubre', 'Noviembre', 'Diciembre'],
            monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Set', 'Oct','Nov','Dic'],
            dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
            dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
            dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
            weekHeader: 'Sm',
            dateFormat: 'yymm',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        };
     $.datepicker.setDefaults($.datepicker.regional['es']);
            $( "#fecha" ).datepicker({
                inline: true,
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
 
            onClose: function (dateText, inst) {
            var mes = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var ano = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            var anomes=$.datepicker.regional['es'].monthNames[mes]+' '+ano;
            mes = parseInt(mes) + 1;
            mes = ('0' + mes).slice(-2);
            $('#fecha').val(anomes);
            document.cookie ='variable1='+ano+'; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
            document.cookie ='variable2='+mes+'; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
                                            }
                                    });
        //obtengo la fecha actual
            var fechaActual = new Date();
            var intMes = fechaActual.getMonth();
            var intAno = fechaActual.getFullYear();
            var mesYear = $.datepicker.regional['es'].monthNames[intMes]+' '+intAno;
        //paso el valor al value del select    
            $('#fecha').val(mesYear);
            document.cookie ='variable1='+intAno+'; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
            document.cookie ='variable2='+intMes+'; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
            //var fechaActual = new Date();
            //var mesActual = fechaActual.getMonth();
            //var mesActual = parseInt(mesActual) + 1;
            //mesActual = ('0' + mesActual).slice(-2);
            //var anoActual = fechaActual.getFullYear();
    });
    </script>
 
        </head>
	<body>
 
            <header>
		<div class="alert alert-info">
                    <h2>Descargar Reportes en Excel de sistema SIGES</h2>
		</div>
            </header>
            <!-- Datepicker -->
            <h2 class="demoHeaders">Kardex Mensual</h2>
            <form action="descarga_reporte.php" method="post">
            <input type="text" name="fecha" value="" id="fecha">
            <button type="submit" name="generar_reporte" class="btn btn-primary">Generar Reporte</button>
            </form>
	</body>
</html>

descarga_reporte.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
<head>
  <script src="./pace/pace.min.js"></script>
  <link href="./pace/themes/black/pace-theme-corner-indicator.css" rel="stylesheet" />
</head>
 
<?php
date_default_timezone_set('America/Lima');
include'conexion.php';//CONEXION A LA BD
include_once 'Classes/PHPExcel.php';
$ano = $_COOKIE['variable1'];
$mes = $_COOKIE['variable2'];
$anomes=$ano.$mes;
$mesactual= date('Ym');
if($mes==12){
    $ano2=$ano+1;
    $mes_siguiente=$ano2.'01';
            }
else{
    $mes_siguiente=$anomes+1;
     }
$tabla2="ventad$mes_siguiente";
$tabla= "ventad$anomes";
$objXLS = new PHPExcel();
$cod=1;
$hojas=0;
//armamos la consulta
$sqlprod="select V.cdarticulo, A.dsarticulo from $tabla V inner join articulo A on V.cdarticulo=A.cdarticulo group by V.cdarticulo,A.dsarticulo order by V.cdarticulo";
//ejecutamos la consulta
$prod=odbc_exec($conexion,$sqlprod);
//obtenemos la cantidad de filas de la consulta 
$numprod= odbc_num_rows($prod);
$i = 0;
while(odbc_fetch_row($prod)) {
     $i++;
     ${"cdprod" . $i} = trim(odbc_result($prod,'cdarticulo'));
     ${"dsprod" . $i} = trim(odbc_result($prod,'dsarticulo'));
}
while($cod<=$numprod)
{
 $objXLS->createSheet();
$objSheet = $objXLS->setActiveSheetIndex($hojas);
if(isset($_POST['generar_reporte']))
{
        // ENCABEZADOS
	$objSheet->setCellValue('C3', 'DOCUMENTO');
        $objSheet->setCellValue('D3', 'CANTIDAD');
        $objSheet->setCellValue('E3', 'SUBTOTAL');
        $objSheet->setCellValue('F3', 'FECHA');
 
	// QUERY PARA CREAR EL REPORTE  
        $numero=3;
        if ($cod==1){
        if ($anomes==$mesactual){
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod1
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod1;
        }else{
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod1
                    union SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla2
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod1
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod1;
        }
        }elseif($cod==2){
        if ($anomes==$mesactual){
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod2
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod2;
        }else{
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod2
                    union SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla2
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod2
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod2;
        }
        }elseif($cod==3){
        if ($anomes==$mesactual){
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod3
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod3;
        }else{
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod3
                    union SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla2
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod3
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod3;
        }
        }elseif($cod==4){
        if ($anomes==$mesactual){
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod4
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod4;
        }else{
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod4
                    union SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla2
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod4
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod4;
        }
        }elseif($cod==5){
        if ($anomes==$mesactual){
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod5
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod5;
        }else{
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod5
                    union SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla2
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod5
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod5;
        }
        }elseif($cod==6){
        if ($anomes==$mesactual){
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod6
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod6;
        }else{
        $sqlventa="SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod6
                    union SELECT fecproceso,nrodocumento,cantidad,mtosubtotal FROM $tabla2
                   where month(fecproceso)=$mes and cdtipodoc=12 and cdarticulo=$cdprod6
                    order by fecproceso,nrodocumento";
        $titulo=$dsprod6;
        }
        }
        $can=odbc_exec($conexion,$sqlventa);
 
        while(odbc_fetch_row($can)){
		$numero++;
		$objSheet->setCellValue('C'.$numero, odbc_result($can, 'nrodocumento'));
		$objSheet->setCellValue('D'.$numero, odbc_result($can, 'cantidad'));
		$objSheet->setCellValue('E'.$numero, odbc_result($can, 'mtosubtotal'));
		$objSheet->setCellValue('F'.$numero, date('d/m/Y',strtotime(odbc_result($can, 'fecproceso'))));
	}
$objXLS->getActiveSheet($hojas)->getColumnDimension('C')->setAutoSize(true);
$objXLS->getActiveSheet($hojas)->getColumnDimension('D')->setAutoSize(true);
$objXLS->getActiveSheet($hojas)->getColumnDimension('E')->setAutoSize(true);
$objXLS->getActiveSheet($hojas)->getColumnDimension('F')->setAutoSize(true);
$objXLS->getActiveSheet($hojas)->setTitle($titulo);
$objXLS->setActiveSheetIndex($hojas);
}
$hojas++;
$cod++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objXLS, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename=Kardex$ano-$mes.xlsx");
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
?>

como quedaria el codigo optimizado.

Graicas

Saludos
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