Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-formula

Distribute equal data evenly to set a print area equally


the official printer is dead. I´ve been assigned to print the payroll receipt for 4k people but the range is variable given the quantity of perceptions for every person, I need to set only 4 receipts per page. So I cant say just every n rows append 3 or 4 empty rows in order to send the next ones to the next page. I´ve been trying something like well if column A is text: true, else, false and on the 5th true, append 4 empty rows before the 5th true. Cant find anything about setting printing options and I´m completely lost, any help would be really appreciated. ty in advance

example link:

https://docs.google.com/spreadsheets/d/1kjSP1NSTGjjo3N4KVEz3sGqCAD-fzJ3ItJeBKuNTfAo/edit#gid=506394686


Solution

  • Use a Reverse For Loop and insertRows()

    I suggest using a reverse for loop in order to avoid mismatch of the indices of the data rows after adding new rows. You may use the following code as a basis to your code:

    function insertSpace() {
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data = ss.getDataRange().getValues();
      var count = 0;
      for(i=data.length; i>0; i--){
        if(data[i-1][6] == "T Total") {
          count ++;
          if (count == 5) {
            count = 1;
            ss.insertRows(i+1,4); //replace 4 to adjust the number of rows added
          }
        }
      }
    }
    

    I used the "T Total" entry to group the data of every individual and used a counter as a basis to add rows.

    NOTE: The script will take some time to process the data especially if you have 4k people's entries to process. Hence, you may start from this logic to create your own code. Also, you may try running this script by batch and not feed all 4k people's entries in one go.

    Output:

    enter image description here

    References