Como generar un funcion que filtre los datos en una hoja en sheet y que eso filtrado me lo muestre en un datatable que tengo un webapp

48 views
Skip to first unread message

Freddy Moreno

unread,
Jul 14, 2024, 12:12:08 AM7/14/24
to Apps Script en Español
Tengo un webapp creado con app scritpt 
En el tengo un input y un datatable 
Con el input agrego el codigo de la cuenta que deberia filtrar todo sin problema, con este codigo se muestra los datos en la tabla

    <? var data = SpreadsheetApp
        .openById('1NCmMOWDSgv6F0hfRpEb-vWFrRGVRkBLxJmIAji-cIpQ')
        .getSheetByName('Data')
        .getRange('A2:F4000')
        .getValues(); ?>



Cuando mantengo el rango en 1000 filas todo funciona bien pero como el rango sera variable y superior a mi cuando coloco 4000, la funcion se torna lenta e incluiso se queda pegada.

Como podria hacer mas optimo mi codigo


<head>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
         
</head>

    <? var data = SpreadsheetApp
        .openById('1NCmMOWDSgv6F0hfRpEb-vWFrRGVRkBLxJmIAji-cIpQ')
        .getSheetByName('Data')
        .getRange('A2:F4000')
        .getValues(); ?>

<main>
  <section class="row">
      <div class="col">
          <div class="card">
            <div class="card-body">
              <form class="row">
                  <div class="form-group col-md-2">
                    <input type="text" class="form-control" id="myInput" form="input-search" placeholder="filtrar Cuenta" onkeyup="filtrar()" >
                  </div>
                  <div class="form-group col-md-2">
                    <input  class="form-control" id="codigo" placeholder="Codigo Cuenta" disabled>
                  </div>
                  <div class="form-group col-md-3">
                    <input class="form-control" id="cuenta" placeholder="Nombre Cuenta" disabled>
                  </div>
                  <div class="form-group col-md-2">
                      <input class="form-control" type="date" id="fechaInicial" placeholder="Fecha Inicial" onchange="filtrarFecha()">
                  </div>
                  <div class="form-group col-md-2">
                      <input class="form-control" type="date" id="fechaFinal" placeholder="Fecha Final" onchange="filtrarFecha()">
                  </div>
                  <div class="form-group col-md-2">
                    <input class="form-control" id="row-count" placeholder="Registros">
                  </div>
                  <div class="form-group col-md-2 right">
                  <input class="form-control d-flex justify-content-between align-items-center" type="number" id="total-monto" placeholder="Monto Total">
                </div>

              </form>
            </div>
          </div>
      </div>
  </section>
</main>

    <button id="filtrarbtn" class="btn btn-float-right mycolor" style="font-size: 1em; float: right;"  onclick="filtrados_a_hoja()">Enviar a Hoja</button>
          <table id="myTable" class="hidden">
                <tr class="header">
                  <th style="width:5%;">Codigo</th>
                  <th style="width:15%;">Cuenta</th>
                  <th style="width:10%;">Fecha</th>
                  <th style="width:15%;">Referencia</th>
                  <th style="width:50%;">Descripcion</th>
                  <th style="width:5%;">Monto</th>
                </tr>

              <? for (var i = 0; i < data.length; i++ ) { ?>
                  <tr>
                    <? for (var j = 0; j < data[i].length; j++ ) { ?>
                      <td><?= data[i][j] ?></td>
                    <? } ?>
                  </tr>
              <? } ?>

          </table>

<script>


    //OCULTAR CAMPOS
    document.getElementById("myInput").addEventListener("input", function() {
        var inputValue = this.value.trim();
        var otherInputs = document.querySelectorAll(".hidden");
        var myTable = document.getElementById("myTable");

        if (inputValue) {
            // Si el input tiene contenido, muestra los elementos ocultos
            otherInputs.forEach(function(input) {
                input.classList.remove("hidden");
            });
            myTable.classList.remove("hidden");
        } else {
            // Si el input está vacío, oculta los elementos
            otherInputs.forEach(function(input) {
                input.classList.add("hidden");
            });
            myTable.classList.add("hidden");
        }
        calculateTotalMonto();
    });

 function filtrar() {
      var input, filter, table, tr, td, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");

      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0]; // Assuming code is in the first column (index 0)
        if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
            // Update hidden fields with matching code and account
            const code = td.textContent;
            const account = tr[i].getElementsByTagName("td")[1].textContent; // Assuming account is in the second column (index 1)
            document.getElementById("codigo").value = code;
            document.getElementById("cuenta").value = account;
          } else {
            tr[i].style.display = "none";
            // Clear hidden fields when no match
            document.getElementById("codigo").value = "";
            document.getElementById("cuenta").value = "";
          }
        }
      }
      calculateTotalMonto(); // Call the function to update totals (if needed)
    }


function filtrarOriginal() {
            // Declare variables
            var input, filter, table, tr, td, i, txtValue;
            input = document.getElementById("myInput");
            filter = input.value.toUpperCase();
            table = document.getElementById("myTable");
            tr = table.getElementsByTagName("tr");

            // Loop through all table rows, and hide those who don't match the search query
            for (i = 0; i < tr.length; i++) {
              td = tr[i].getElementsByTagName("td")[0];
              if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                  tr[i].style.display = "";
                          calculateTotalMonto();
                } else {
                  tr[i].style.display = "none";
                          calculateTotalMonto();
                }
              }
            }
        calculateTotalMonto();
   
}

function filtrados_a_hoja()
          {
            try {
            var mat = [];
            var tabla = document.getElementById("myTable");
            var tr = tabla.getElementsByTagName("tr");
             for(i = 1; i < tr.length; i++){
              if(tr[i].style.display !== 'none'){
                datos = [
                          tr[i].getElementsByTagName("td")[0].innerText,
                          tr[i].getElementsByTagName("td")[1].innerText,
                          tr[i].getElementsByTagName("td")[2].innerText,
                          tr[i].getElementsByTagName("td")[3].innerText,
                          tr[i].getElementsByTagName("td")[4].innerText,
                          tr[i].getElementsByTagName("td")[5].innerText
                        ];
                mat.push(datos);
              };
             }
              //console.log(mat);
              google.script.run.escribirDatosFiltrados(mat);
              limpiar();
              } catch (error) {
            console.error(error); // Log the error for debugging
    // Optionally, handle the error gracefully (e.g., display an error message)
            }
                       
}

function confirmarGenerarMayor() {
              try {
      // Pregunta al usuario si desea continuar
      Swal.fire({
        title: "Confirmación",
        text: "¿Deseas generar el mayor?",
        icon: "question",
        timer: 5000,
        showCancelButton: true,
        confirmButtonText: "Sí",
        cancelButtonText: "Cancelar",
      }).then((result) => {
        if (result.isConfirmed) {
          // El usuario aceptó, ejecuta la función
         
          Swal.fire({
            title: "Mayor Generado",
            text: "Generado Exitosamente",
            icon: "success"
          });

          //filtrados_a_hoja();
        } else {
          // El usuario canceló, no hagas nada
            Swal.fire({
            title: "Mayor Generado",
            text: "Operacion anulada",
            icon: "warning"
          });
        }
      });
              } catch (error) {
            console.error(error); // Log the error for debugging
    // Optionally, handle the error gracefully (e.g., display an error message)
}


}


function calculateTotalMonto() {
  var table = document.getElementById("myTable");
  var tbody = table.getElementsByTagName("tbody")[0];
  var totalMonto = 0;
  var rowCount = 0; // Initialize row count

  // Loop through visible rows, excluding the header row
  for (var i = 1; i < tbody.rows.length; i++) { // Start from row 1 to exclude header
    if (tbody.rows[i].style.display !== 'none') {
      rowCount++; // Increment row count

      var montoCell = tbody.rows[i].cells[5]; // Assuming monto is in the 6th column (index 5)
      var montoValue = parseFloat(montoCell.textContent);
      if (!isNaN(montoValue)) {
        totalMonto += montoValue;
      }
    }
  }

  document.getElementById("total-monto").value = totalMonto.toFixed(2);
  document.getElementById("row-count").value = rowCount; // Update row count input field

}


</script>

      <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/boot...@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
      <script src="https://cdn.datatables.net/2.0.2/js/dataTables.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <!--  <?!= HtmlService.createHtmlOutputFromFile('js').getContent() ?> --->



Anexo el codigo completo, su ayuda si debo manejar el codigo de otra manera o que debo modificar para que simplifique la busqueda

Su ayuda


Reply all
Reply to author
Forward
0 new messages