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

Retrieve values from google sheet to google slides are not populating results


I have a Google sheet table.

enter image description here

I want to transfer this data into Google Slides. I have the following code:

var templateId = "XXX";
var presentationTemplate = DriveApp.getFileById(templateId);
var copy = presentationTemplate.makeCopy();

The objective is to create slides for each row. The design for each slide is different. First slide is in table and second slide has a text.

function newPresentation () {

let templateId = "XXX";
let presentationTemplate = DriveApp.getFileById(templateId);
let copy = presentationTemplate.makeCopy().getId();
let deck = SlidesApp.openById(copy);
let slides = deck.getSlides();

// Load data from the spreadsheet.

  let dataRange = SpreadsheetApp.getActive().getDataRange();
  let sheetContents = dataRange.getValues();
  
sheetContents.forEach(function (row) {

    // Insert a new slide by duplicating the master slide.
    let firstSlide =  slides[0];
    let secondSlide = slides[1];
    
    

    // Populate data in the slide that was created
    firstSlide.replaceAllText("{{item}}", row[0]);
    firstSlide.replaceAllText("{{item}}", row[1]);
    secondSlide.replaceAllText("{{item}}", row[0]);
    secondSlide.replaceAllText("{{item}}", row[1]);
    
})

}

Solution

  • From your provided template Slide, I understood your expected result is as follows.

    • You have a template Slide including 2 pages. And, you have a Google Spreadsheet in your showing image.
    • All pages have 2 place holders of {{item}} and {{results}}.
    • You want to replace the 1st page with 2nd row values and want to replace the 2nd page with 3rd row values.

    In this case, how about the following modification?

    In your showing script, the 1st header row is retrieved. In your situation, the 1st header row is required to be skipped. And, the number of loops is required to depend on the number of slide pages.

    Modified script:

    function newPresentation() {
      let templateId = "XXX";
      let presentationTemplate = DriveApp.getFileById(templateId);
      let copy = presentationTemplate.makeCopy().getId();
      let deck = SlidesApp.openById(copy);
      let slides = deck.getSlides();
      let dataRange = SpreadsheetApp.getActive().getDataRange();
    
    
      // I modified the below script.
      const ar = ["{{item}}", "{{results}}"]; // Sample object for replacing the placeholders.
      const [, ...sheetContents] = dataRange.getDisplayValues();
      slides.forEach((slide, i) => ar.forEach((f, j) => slide.replaceAllText(f, sheetContents[i][j])));
    }
    
    • When this script is run, the placeholders of "{{item}}" and "{{results}}" on the 1st page are replaced with "A" and "This is item A". And, the placeholders of "{{item}}" and "{{results}}" on the 2nd page are replaced with "B" and "This is item B".