lunes, 2 de septiembre de 2019

Descargar excel con ajax y json

Muchas veces queremos enviar datos JSON a un porcesador de PHP, para luego hacer un reporte en XLSX(Excel) o PDF. Pero hemos falladao en el intento, porque intentamos hacerlo con JQUERY y no funciona. En vista de ello, en este tutorial vamos aprender hacerlo usando AJAX Puro de JavaScript. Para ello vamos a usar la libreria PhpSpreadsheet para convertir los datos recogido por el PHP en XLSX, que luego podremos descargar

Archivo: JS, donde se crea la funcion AJAX para enviar los datos JSON hacia un archivo PHP

function enviar_jsonDescargarXLSX(ArrayJson,procesadorphp,NombreArchivoDescarga,capaeventosid){
  var JsonEnviar=JSON.stringify(ArrayJson);
  var xhr = new XMLHttpRequest();
  xhr.open("POST", procesadorphp, true);
  xhr.responseType = 'blob';
  //Envíe la información de encabezado adecuada junto con la solicitud
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.onload = function (e) {
      if (xhr.readyState === 4 && xhr.status === 200) {
          var contenidoEnBlob = xhr.response;
          var link = document.createElement('a');
          link.href = (window.URL || window.webkitURL).createObjectURL(contenidoEnBlob);
          link.target="_blank";
          //Darle un nombre al Archivo a descargar
          link.download=NombreArchivoDescarga;
          var clicEvent = new MouseEvent('click', {
              'view': window,
              'bubbles': true,
              'cancelable': true
          });
          //Simulamos un clic del usuario
          link.dispatchEvent(clicEvent);
          //link.click();
          $(capaeventosid).html("Archivo ("+NombreArchivoDescarga+") Descargado !!!")
      } else {
          $(capaeventosid).html(" No es posible acceder al archivo, probablemente no existe.")
      }
  };
  xhr.send("jsonenviado="+JsonEnviar);
}

Archivo HTML o PHP, desde donde se envia la peticion por javascript. Notese que lo estoy combinando con codigos PHP. Ademas aqui se pone el nombre deseado del archivo a descargar.

var Json=[];
var item;
var pptoID=document.getElementsByName("PPTOID[]");
var detalleID=document.getElementsByName("detalleID[]");
var costoID=document.getElementsByName("costoID[]")
var numeracion=document.getElementsByName("numeracion[]");
var tipocosto=document.getElementsByName("tipocosto[]");
var descripcion=document.getElementsByName("descripcion[]");
var unimed=document.getElementsByName("unimedcosto[]");
var p_nombre=document.getElementsByName("p_nombre[]");
var p_cantidad=document.getElementsByName("p_cantidad[]");
var p_p_unitario=document.getElementsByName("p_p_unitario[]");
var p_p_parcial=document.getElementsByName("p_p_parcial[]");
var c_cantidad=document.getElementsByName("c_cantidad[]");
var c_p_unitario=document.getElementsByName("c_p_unitario[]");
var c_p_parcial=document.getElementsByName("c_p_parcial[]");
var montoganancia=document.getElementsByName("montoganancia[]");
var porcentajeganancia=document.getElementsByName("porcentajeganancia[]");
var cotizador=document.getElementsByName("cotizador[]");
var observaciones=document.getElementsByName("observaciones[]");
for (var i = 0; i < descripcion.length; i++) {
 detalleID[i].value="";
 pptoID[i].value="";
 item={
  CostosID:costoID[i].value,
  DetalleID:detalleID[i].value,
  PPTOID:pptoID[i].value,
  tipocostoID:tipocosto[i].value,
  Numeracion:numeracion[i].value,
  Descripcion:encodeURI(descripcion[i].value),
  UniMed:unimed[i].value,
  CantidadCliente:c_cantidad[i].value,
  P_unitarioCliente:c_p_unitario[i].value,
  P_parcialCliente:c_p_parcial[i].value,
  Provee_cantidad:p_cantidad[i].value,
  Provee_p_unitario:p_p_unitario[i].value,
  Provee_p_parcial:p_p_parcial[i].value,
  NombreProveedor:p_nombre[i].value,
  MontoGanancia:montoganancia[i].value,
  Porcentaje_diferencia:porcentajeganancia[i].value,
  NombreCotizador:cotizador[i].value,
  Observaciones:observaciones[i].value
 };
 Json.push(item);
}
var JsonPPTO={
 DetalleID:"",
 NombreProvedorGeneral:"Varios",
 NombreCotizadorGeneral:"Varios",
 SumaTotalProveedores:document.frmcosto_detalle.TotalDetalleProveedor.value,
 SumaTotalCliente:document.frmcosto_detalle.TotalDetalleCliente.value,
 SumaUtilidad:document.frmcosto_detalle.TotalDetalleMontoUtilidad.value,
 PorcentajeGanancia:document.frmcosto_detalle.TotalDetalleporcentajeUtilidad.value,
 detIdppto:"",
 PPTOID: "",
 DescripcionDetalle:"",
 items:Json
};
//Aqui Llamamos a la funcion creada en el JS externo
enviar_jsonDescargarXLSX(JsonPPTO,"presupuestos_exporta_excel.php?op=ExportarCostosXDetalleId","PPTO- -  - ","#divEnventosCosto");

Archivo:PHP, que en mi ejemplo sera presupuestos_exporta_excel.php, Notese que estoy tomando una plantilla .XLSX existen en el servidor, NO estoy creando el archivos desde CERO.

<?php
require_once("../libreria.php");
require '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
$op=coger_dato_externo("op");
switch ($op) {
 case 'ExportarCostosXDetalleId':
  $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('../vendor/DetalleCostoPPTOxIdDetalle.xlsx');
  $worksheet = $spreadsheet->getActiveSheet();
  $JSON=coger_dato_externo("jsonenviado");
  $datosJson=json_decode($JSON);
  #Detalles para redireccionamiento
  $detIdppto=$datosJson->{"detIdppto"};
  #Detalles Importantes
  $PPTOID=$datosJson->{"PPTOID"};
  $DetalleID=$datosJson->{"DetalleID"};
  $DescripcionDetalle=$datosJson->{"DescripcionDetalle"};
  $NombreProvedorGeneral=$datosJson->{"NombreProvedorGeneral"};
  $NombreCotizadorGeneral=$datosJson->{"NombreCotizadorGeneral"};
  $SumaTotalProveedores=$datosJson->{"SumaTotalProveedores"};
  $SumaTotalCliente=$datosJson->{"SumaTotalCliente"};
  $SumaUtilidad=$datosJson->{"SumaUtilidad"};
  $PorcentajeGanancia=$datosJson->{"PorcentajeGanancia"};
  $cantidadErrores=0;
  $filas=0;
  $sqlInsetarDetalleCostoPPTO="";
  $ListaPPTOBusqueda2=array();
  foreach ($datosJson->{"items"} as $datosrecogidos) {
   
   $CostosID=$datosrecogidos->{"CostosID"};
   $DetalleID=$datosrecogidos->{"DetalleID"};
   $PPTOID=$datosrecogidos->{"PPTOID"};
   $TipocostoID=$datosrecogidos->{"tipocostoID"};
   $Numeracion=$datosrecogidos->{"Numeracion"};
   $Descripcion=$datosrecogidos->{"Descripcion"};
   $UniMed=$datosrecogidos->{"UniMed"};
   $CantidadCliente=$datosrecogidos->{"CantidadCliente"};
   $P_unitarioCliente=$datosrecogidos->{"P_unitarioCliente"};
   $P_parcialCliente=$datosrecogidos->{"P_parcialCliente"};
   $Provee_cantidad=$datosrecogidos->{"Provee_cantidad"};
   $Provee_p_unitario=$datosrecogidos->{"Provee_p_unitario"};
   $Provee_p_parcial=$datosrecogidos->{"Provee_p_parcial"};
   $NombreProveedor=$datosrecogidos->{"NombreProveedor"};
   $MontoGanancia=$datosrecogidos->{"MontoGanancia"};
   $Porcentaje_diferencia=$datosrecogidos->{"Porcentaje_diferencia"};
   $NombreCotizador=$datosrecogidos->{"NombreCotizador"};
   $Observaciones=$datosrecogidos->{"Observaciones"};
   $ListaPPTOBusqueda2[$filas][0]=$Descripcion;
   $ListaPPTOBusqueda2[$filas][1]=$UniMed;
   $ListaPPTOBusqueda2[$filas][2]=$NombreProveedor;
   $ListaPPTOBusqueda2[$filas][3]=$Provee_cantidad;
   $ListaPPTOBusqueda2[$filas][4]=$Provee_p_unitario;
   $ListaPPTOBusqueda2[$filas][5]=$Provee_p_parcial;
   $ListaPPTOBusqueda2[$filas][6]=$CantidadCliente;
   $ListaPPTOBusqueda2[$filas][7]=$P_unitarioCliente;
   $ListaPPTOBusqueda2[$filas][8]=$P_parcialCliente;
   $ListaPPTOBusqueda2[$filas][9]=$MontoGanancia;
   $ListaPPTOBusqueda2[$filas][10]=$Porcentaje_diferencia;
   $ListaPPTOBusqueda2[$filas][11]=$NombreCotizador;
   $ListaPPTOBusqueda2[$filas][12]=$Observaciones;
   $filas+=1;
  }

  $FechaActual=date("d") . " del " . date("mm") . " de " . date("Y");
  $Letrainicial=5; #Desde la fila que empezara a llenar los datos
  
  $worksheet->getCell('B2')->setValue($DescripcionDetalle);
  $worksheet->getCell('B1')->setValue("PPTO: ".$PPTOID);
  $worksheet->getCell('C1')->setValue($FechaActual);
  

  ini_set('max_execution_time', 900); // 120 (seconds) = 2 Minutes
  ini_set('memory_limit','512M');
  
  $spreadsheet->getActiveSheet()->insertNewRowBefore($Letrainicial+1, $filas);
  $spreadsheet->getActiveSheet()
      ->fromArray(
          $ListaPPTOBusqueda2,  // The data to set
          NULL,        // Array values with this value will not be set
          'B'.$Letrainicial         // Top left coordinate of the worksheet range where
                       //    we want to set these values (default is A1)
      );
  $spreadsheet->getActiveSheet()->removeRow($filas+$Letrainicial, 2);
  $spreadsheet->getActiveSheet()->setCellValue(
      'G'.($filas+$Letrainicial),
      '=SUM(G'.$Letrainicial.':G'.($filas+$Letrainicial-1).')' # las formulas tienen que estar en ingles
  );
  $spreadsheet->getActiveSheet()->setCellValue(
      'J'.($filas+$Letrainicial),
      '=SUM(J'.$Letrainicial.':J'.($filas+$Letrainicial-1).')'
  );
  $spreadsheet->getActiveSheet()->setCellValue(
      'K'.($filas+$Letrainicial),
      '=SUM(K'.$Letrainicial.':K'.($filas+$Letrainicial-1).')'
  );
  $spreadsheet->getActiveSheet()->setCellValue(
      'L'.($filas+$Letrainicial),$PorcentajeGanancia
  );
  $styleArray = [
      'borders' => [
          'top' => [
              'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
              'color' => ['argb' => '000000'],
          ],
      ],
  ];

  $worksheet->getStyle('B'.($filas+$Letrainicial).':N'.($filas+$Letrainicial))->applyFromArray($styleArray);
  // Redirect output to a client’s web browser (Xlsx)
  header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  header('Content-Disposition: attachment;filename="PPTO-'.$PPTOID."-".$DetalleID."-".$DescripcionDetalle.'"');
  header('Cache-Control: max-age=0');
  // If you're serving to IE 9, then the following may be needed
  header('Cache-Control: max-age=1');

  // If you're serving to IE over SSL, then the following may be needed
  header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
  header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  header('Pragma: public'); // HTTP/1.0
  $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
  $writer->save('php://output');
  break;
 
 default:
  # code...
  break;
}
?>

1 comentario:

  1. Recamedi: Descargar Excel Con Ajax Y Json >>>>> Download Now

    >>>>> Download Full

    Recamedi: Descargar Excel Con Ajax Y Json >>>>> Download LINK

    >>>>> Download Now

    Recamedi: Descargar Excel Con Ajax Y Json >>>>> Download Full

    >>>>> Download LINK fN

    ResponderEliminar

Crud Simple en laravel 8