PHP - consulta filtrada y descarga excel

 
Vista:
sin imagen de perfil

consulta filtrada y descarga excel

Publicado por Hugo (37 intervenciones) el 19/02/2022 18:10:24
Hola, buenas tardes amigos.

Tengo el siguiente problema que no sé como resolver:

Tengo una pagina donde se consultan las licencias existentes filtradas por fecha y/o tipo de licencia a través de un botón (visualizar).
La consulta se ejecuta correctamente y se cargan los datos, sin embargo cuando quiero descargarlo a Excel con otro botón para la descarga, el archivo me sale vacío.
Entiendo es porque no puedo en el action del form utilizar $_SERVER['PHP_SELF'] y a su vez enviar las variables obtenidas de los filtros a excel.php.

Alguien sabe como puedo lograr esto?, desde ya agradezco mucho si alguien me puede ayudar porque le estoy dando vueltas y no sé como resolverlo.

Pego el código:

Consulta de licencias:

<html>
<head>
<title>Intranet</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="../Cabecera/cabecera.css">
<!--link rel="stylesheet" type="text/css" href="../Login/iniciar_session.css">
<link rel="stylesheet" type="text/css" href="../Avatar/avatar.css">
<link rel="stylesheet" type="text/css" href="../Internacion/internacion2.css">
<link rel="stylesheet" type="text/css" href="../Formato_Form/formularios.css"-->
<link rel="stylesheet" type="text/css" href="consulta_lic_espec.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Kaisei+HarunoUmi:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.0/sweetalert2.css"/>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.0/sweetalert2.js"></script>
</head>
<body>
<?php
include ("../Conexion/conexion.php");
?>
<div id="Cabecera">
<?php
require ("../Login/iniciar_session.php");
?>
</div>

<div class="volver">
<a href="gestion_rrhh.php"><button type="button" class="btn btn-danger btn">Volver</button></a>
</div>

<div id="#">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" class="form">
<div class="formulario">
<h2 class="titulo">Consulta Licencias Especiales</h2><br><br>
<div class="fechas" >
<span>Desde:
<input type="date" name="desde" class="fecha" required/></span>
<span class="Hasta">Hasta:
<input type="date" name="hasta" class="fecha" required/>
Tipo de Licencia: <select name="tipo" class="tipo">
<option>Todas</option>
<option>Cita Judicial</option>
<option>Donacion de sangre</option>
<option>Fallecimiento</option>
<option>Hijo discapacitado</option>
<option>Internacion</option>
<option>Matrimonio</option>
<option>PAP-MAMO</option>
<option>Licencia por Congreso</option>
<option>Licencia por Estudio</option>
<option>Violencia de genero</option>


</select> <input type="submit" value="Visualizar" name="ver" class="btn btn-primary btn">
</span>
</div>
</div>
</form>

<?php

//error_reporting(E_ERROR | E_WARNING | E_PARSE);
date_default_timezone_set("America/Montevideo");
if(isset($_POST['ver'])){
$desde=$_POST['desde'];
$hasta=$_POST['hasta'];
$tipo=$_POST['tipo'];

if($tipo=='Todas'){
$datos="SELECT * FROM licespec WHERE (fechaDesde>='$desde' && fechaDesde<='$hasta') && estado='Autorizado' ORDER BY fechaDesde DESC";
$query_datos=$conexion->query($datos);
}else{
$datos="SELECT * FROM licespec WHERE (fechaDesde>='$desde' && fechaDesde<='$hasta') && tipoLic='$tipo' && estado='Autorizado' ORDER BY fechaDesde DESC";
$query_datos=$conexion->query($datos);
}

?>

<div class="col-md-8-sm">
<br><table class="table table-striped table-responsive table-sm table-hover table-bordered">
<thead class="encabezado" >
<tr>
<th>N° Solic.</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Sección</th>
<th>Licencia</th>
<th>Descripción</th>
<th>Desde</th>
<th>Hasta</th>
<th>Cant. de Días</th>
<th>Fecha de Solicitud</th>
<th>Estado</th>
<th>Fecha de Autorización</th>
</tr>
</thead>
<tbody>
<?php
while($array_datos=$query_datos->fetch_assoc()){
$fecha_desde=$array_datos['fechaDesde'];
$desde=strtotime($fecha_desde);
$f_desde=date('d-m-Y',$desde);

$fecha_hasta=$array_datos['fechaHasta'];
$hasta=strtotime($fecha_hasta);
$f_hasta=date('d-m-Y',$hasta);

$fecha_solicitud=$array_datos['fechaSolicitud'];
$solic=strtotime($fecha_solicitud);
$f_solic=date('d-m-Y',$solic);

$fecha_autorizacion=$array_datos['fechaAutorizacion'];
$autoric=strtotime($fecha_autorizacion);
$f_autoric=date('d-m-Y',$autoric);
?>
<tr>
<th><?php echo $array_datos['idSolic']?></th>
<th><?php echo $array_datos['nombre']?></th>
<th><?php echo $array_datos['apellido']?></th>
<th><?php echo $array_datos['seccion']?></th>
<th><?php echo $array_datos['tipoLic']?></th>
<th><?php echo $array_datos['descripcion']?></th>
<th><?php echo $f_desde?></th>
<th><?php echo $f_hasta?></th>
<th><?php echo $array_datos['cantDias']?></th>
<th><?php echo $f_solic?></th>
<?php
if($array_datos['estado']==NULL){
echo '<th>'. '</th>';
}else{
echo '<th style="background-color:#AEFE8B">'.$array_datos['estado']. '</th>';
}
?>
<th><?php
if($array_datos['fechaAutorizacion']==NULL){
echo '';
}else{
echo $f_autoric;
}
?></th>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<a href="excel.php" class="btn btn-primary btn">Descargar</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</div>

</body>
</html>

Archivo excel.php:


<meta charset="utf-8">
<?php

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename= licespec.xls");
?>

<table class="table table-striped table-responsive table-sm table-hover table-bordered">
<thead class="encabezado" >
<h3>Licencias Especiales</h3>
<tr>
</tr>

<tr>
<th>N° Solic.</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Sección</th>
<th>Licencia</th>
<th>Descripción</th>
<th>Desde</th>
<th>Hasta</th>
<th>Cant. de Días</th>
<th>Fecha de Solicitud</th>
<th>Estado</th>
<th>Fecha de Autorización</th>
</tr>
</thead>
<tbody>
<?php
include ("../Conexion/conexion.php");


//error_reporting(E_ERROR | E_WARNING | E_PARSE);
date_default_timezone_set("America/Montevideo");
if(isset($_POST['ver'])){
$desde=$_POST['desde'];
$hasta=$_POST['hasta'];

$datos="SELECT * FROM licespec WHERE (fechaDesde>='$desde' && fechaDesde<='$hasta') && estado='Autorizado' ORDER BY fechaDesde DESC";
$query_datos=$conexion->query($datos);
?>
<?php
echo '<p>'.'Período: '.$desde.' - '.$hasta.'</p>';
?>
<?php
while($array_datos=$query_datos->fetch_assoc()){
$fecha_desde=$array_datos['fechaDesde'];
$desde=strtotime($fecha_desde);
$f_desde=date('d-m-Y',$desde);

$fecha_hasta=$array_datos['fechaHasta'];
$hasta=strtotime($fecha_hasta);
$f_hasta=date('d-m-Y',$hasta);

$fecha_solicitud=$array_datos['fechaSolicitud'];
$solic=strtotime($fecha_solicitud);
$f_solic=date('d-m-Y',$solic);

$fecha_autorizacion=$array_datos['fechaAutorizacion'];
$autoric=strtotime($fecha_autorizacion);
$f_autoric=date('d-m-Y',$autoric);
?>
<tr>
<th><?php echo $array_datos['idSolic']?></th>
<th><?php echo $array_datos['nombre']?></th>
<th><?php echo $array_datos['apellido']?></th>
<th><?php echo $array_datos['seccion']?></th>
<th><?php echo $array_datos['tipoLic']?></th>
<th><?php echo $array_datos['descripcion']?></th>
<th><?php echo $f_desde?></th>
<th><?php echo $f_hasta?></th>
<th><?php echo $array_datos['cantDias']?></th>
<th><?php echo $f_solic?></th>
<?php
if($array_datos['estado']==NULL){
echo '<th>'. '</th>';
}else{
echo '<th style="background-color:#AEFE8B">'.$array_datos['estado']. '</th>';
}
?>
<th><?php
if($array_datos['fechaAutorizacion']==NULL){
echo '';
}else{
echo $f_autoric;
}
?></th>
</tr>
<?php
}
?>

<?php
}
?>

</tbody>
</table>
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
sin imagen de perfil

consulta filtrada y descarga excel

Publicado por Antonio (16 intervenciones) el 27/02/2022 13:41:44
Debes primero crear el archivo en excel y guardarlo para después descargarlo (ejemplo en: https://escueladepostgrado.000webhostapp.com/prueba.php) tambien podrías utilizar librerías (https://www.ribosomatic.com/articulos/phpexcel-libreria-php-para-leer-y-escribir-archivos-de-excel/) pero si quieres parecido a tu codigo lo unico que el excel al abrirlo dice que no tiene el mismo formato
<html>
<head>
<title>Intranet</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<link rel="stylesheet" type="text/css" href="consulta_lic_espec.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Kaisei+HarunoUmi:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.0/sweetalert2.css"/>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.0/sweetalert2.js"></script>
</head>
<body>

<div id="Cabecera">

</div>

<div class="volver">
<a href="gestion_rrhh.php"><button type="button" class="btn btn-danger btn">Volver</button></a>
</div>

<div id="#">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" class="form">
<div class="formulario">
<div class="fechas" >
<span>Desde:
<input type="date" name="desde" class="fecha" required/></span>
<span class="Hasta">Hasta:
<input type="date" name="hasta" class="fecha" required/>
</select> <input type="submit" value="Visualizar" name="ver" class="btn btn-primary btn">
</span>
</div>
</div>
</form>

<?php
include 'conect.php';
$shtml="<table>";
$shtml=$shtml."<tr>";
$shtml=$shtml."<td>Nombre</td><td>Fecha</td><td>TipoLicencia</td></tr>"; // Cabecera con nombres de campo


if(isset($_POST['ver'])){
$desde=$_POST['desde'];
$hasta=$_POST['hasta'];

$sql = "SELECT * FROM Productos where Fecha BETWEEN '" . $desde . "' AND '" . $hasta . "'";
$result = $conn->query($sql);

$file = fopen('archivo.xls', 'w');
fwrite($file, "code\tname\tpopulation\t\n");
if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
fwrite ($file, $row ['Nombre']."\t".$row ['Fecha']."\t".$row ['TipoLicencia']."\t\n");
$nom = $row["Nombre"];
$edat=$row["Fecha"];
$tipo = $row["TipoLicencia"];
$shtml=$shtml."<tr>
<td>".$nom."</td>
<td>".$edat."</td>
<td>".$tipo."</td>
</tr>";
}

}

}
$shtml=$shtml."</table>";

fclose($file);
echo $shtml;

?>


<br>

</tbody>
</table>

<a href="archivo.xls" class="btn btn-primary btn">Descargar</a>

<?php

?>

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</div>

</body>
</html>

Archivo excel.php:


<meta charset="utf-8">
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
sin imagen de perfil

consulta filtrada y descarga excel

Publicado por Hugo (37 intervenciones) el 01/03/2022 01:18:50
Estimado Antonio, te agradezco mucho por el tiempo que te has tomado para poder ayudarme.
Voy a utilizar el código sugerido y te comento.

Muchas gracias.
Saludos.
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