Search code examples
google-sheetsgoogle-apps-script

Copy with format


I want to make a script that can research the value entered and copy the results in antoher sheet, the rows is copied but I want to copy the rows with their format can you help me ?

And if you can help me to always copy the first row of the source sheet to the destination sheet with the format I'm down.

function filtrerDonnees() {
  // Récupérer la valeur saisie par l'utilisateur
  var valeurSaisie = Browser.inputBox("Entrez la valeur à rechercher :");

  // Obtenir la feuille active
  var feuille = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var derniereLigne = feuille.getLastRow();

  // Obtenir les données de la plage A2:M100
  var plage = feuille.getRange("A2:P"+derniereLigne);
  var valeurs = plage.getValues();

  // Déclarer un tableau pour stocker les lignes correspondantes
  var tableau = [];

  // Parcourir les lignes
  for (var i = 0; i < valeurs.length; i++) {
    var ligneCorrespondante = false;

    // Parcourir les colonnes de chaque ligne
    for (var j = 0; j < valeurs[i].length; j++) {
      // Vérifier si la cellule correspond à la valeur saisie
      if (valeurs[i][j].toString().toLowerCase().indexOf(valeurSaisie.toLowerCase()) !== -1) {
        ligneCorrespondante = true;
        break;
      }
    }

    // Si la ligne correspond, l'ajouter au tableau
    if (ligneCorrespondante) {
      tableau.push(valeurs[i]);
    }
  }

  // Demander un nom de feuille
  var nomFeuille = Browser.inputBox("Nom de la feuille à créer :");

  // Créer une nouvelle feuille avec le nom spécifié
  var nouvelleFeuille = SpreadsheetApp.getActiveSpreadsheet().insertSheet(nomFeuille);

  // Ajouter les données dans la nouvelle feuille
  if (tableau.length > 0) {
    // Copier les valeurs dans la nouvelle feuille
    nouvelleFeuille.getRange(1, 1, tableau.length, tableau[0].length).setValues(tableau);

  } else {
    // Si aucune ligne ne correspond, afficher un message dans la nouvelle feuille
    nouvelleFeuille.getRange(1, 1).setValue("Aucune ligne ne correspond à la valeur saisie.");
  }
  
  // Insérer une image (bouton) dans la feuille de résultats
  var boutonImage = "https://www.gstatic.com/images/icons/material/system/1x/delete_black_48dp.png";
  nouvelleFeuille.insertImage(boutonImage, 18, 2, 24, 0); // Insérer l'image dans la cellule B2
  
  // Ajouter un déclencheur pour exécuter la fonction supprimerFeuille() lors du clic sur l'image
  var images = nouvelleFeuille.getImages();
  var image = images[images.length - 1];
  image.assignScript('supprimerFeuille');
}

function supprimerFeuille() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  spreadsheet.deleteSheet(sheet);
}

I tried to copy the rows in an array but I think this is why the format is not copied and I haven't found any solution.

Thanks for your time :)


Solution

  • The script was modified to utilize the copyTo destination method which copies all content and formatting;

    function filtrerDonnees() {
      var input1 = Browser.inputBox("Entrez la valeur à rechercher :");
      var ash = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var ashlr = ash.getLastRow();
      var ashlc = ash.getLastColumn();
      var ashsr = 2;
      var ashrg = ash.getRange("A2:P" + ashlr);
      var ashvs = ashrg.getValues();
      var rgtbl = [];//array of rows that contain input1
      for (var i = 0; i < ashvs.length; i++) {
        var bool1 = false;
        for (var j = 0; j < ashvs[i].length; j++) {
          if (ashvs[i][j].toString().toLowerCase().indexOf(input1.toLowerCase()) !== -1) {
            bool1 = true;
            break;
          }
        }
        if (bool1) {
          rgtbl.push({range:ash.getRange(i + ashsr,1,1,ashlc)});//an array of row ranges that contain input1
        }
      }
      var input2 = Browser.inputBox("Nom de la feuille à créer :");
      var nsh = SpreadsheetApp.getActiveSpreadsheet().insertSheet(input2);
      if (rgtbl.length > 0) {
        rgtbl.forEach((obj,k) => { obj.range.copyTo(nsh.getRange(k + 1,1)) })
      } else {
        nsh.getRange(1, 1).setValue(`No rows found containing ${input1} in ${ash.getName()}`);
      }
      var img1 = "https://www.gstatic.com/images/icons/material/system/1x/delete_black_48dp.png";
      nsh.insertImage(img1, 18, 2, 24, 0);
      var images = nsh.getImages();
      var image = images[images.length - 1];
      image.assignScript('delSheet');
    }
    
    function delSheet() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sh = ss.getActiveSheet();
      ss.deleteSheet(sh);
    }
    

    I have not tested this code so some debugging may be required. But since we are all programmers here I am leaving that up to the user of this code. I assume that the user can do the same thing that I had to do. Which was to read the code and review the documentation to determine what it does and how you need to change it to accommodate your needs.