Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-slides

How do you take Google Sheet values from more than one row and make it a variable?


function fillTemplate() {
  var Presentation = SlidesApp.openById("1ru6dikBajTPNRBE4YC-GJ8oorm_aaVvysF5fbLKhRYo");
  var sh = SpreadsheetApp.openById("14zPDJrdMprcqA8gbAnnTMbIwE-Malcv6aKUvivRg6I8").getSheetByName("Sheet1");
  var [header, ...values] = sh.getDataRange().getDisplayValues();
  values.forEach(row =>
    row.forEach((col, j) => Presentation.replaceAllText(header[j], col))
  );
Logger.log(header)
}

the code takes variables from a google sheet and replaces google slide variables with the text that is one row below them. i want the header to take from more than one row in my google sheet array but it only takes from the top one, as indicated by the logs showing one row but not any other. i would make everything go on the same row but it would be extremely hard to organise.

i tried to take the column and values row exclusively, change up the col and j table but this is the only one that works somewhat. the working slide template, the not working slide template and google sheet is below.

working

not working

google sheet array

thanks for your time! (sorry if this is a stupid question im new to js)


Solution

  • In your showing script, only the 1st row is used as the header row. From your google sheet array, it seems that the odd rows are the header rows. If my understanding is correct, how about the following sample script?

    Sample script:

    function fillTemplate() {
      var Presentation = SlidesApp.openById("1ru6dikBajTPNRBE4YC-GJ8oorm_aaVvysF5fbLKhRYo");
      var sh = SpreadsheetApp.openById("14zPDJrdMprcqA8gbAnnTMbIwE-Malcv6aKUvivRg6I8").getSheetByName("Sheet1");
      var values = sh.getDataRange().getDisplayValues();
      var obj = [...Array(Math.ceil(values.length / 2))].reduce((m, _) => {
        var [h, v] = values.splice(0, 2);
        v.forEach((e, i) => {
          if (h[i]) m.set(h[i], e);
        });
        return m;
      }, new Map());
      [...obj].forEach(e => Presentation.replaceAllText(...e));
    }
    

    Note:

    • Unfortunately, I cannot know your actual Spreadsheet and Slide. When my proposed script was not useful for your actual situation, can you provide the sample Spreadsheet and Slide? By this, I would like to confirm it.

    References: