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

How to copy a range from a spreadsheet as an image to Google Slides?


I am trying to copy a range of cells of a specific Google spreadsheet as an image onto a Google slide. But I could barely find useful code. This is what I came up with, but I still cannot transfer the cell range into an image/png.

Goal: Insert the image stored just in a variable to a specific slide!

function add_WSA(){
  //Opening the Spreadsheet
  var ss = SpreadsheetApp.openById("insertSpreadsheetID");
  var range = ss.getRange("example!A1:F20");//in A1 Notation
  //Conversion into an png image
  var image = range.getAs('image/png');
  
  //Opening the specific Slide (Nr. 3)
  var slide = SlidesApp.openById("mySlidesID").getSlides()[2]; 
  
  //Insertion of image
  slide.insertImage(image);
}

Error: TypeError: range.getAs is not a function
    at add_WSA(report:5:21)

Solution

  • Issue and workaround:

    Unfortunately, in the current stage, the range object cannot be directly converted to the PNG format. So in this case, it is required to use a workaround. In this answer, as the workaround, I would like to propose to use Charts Service. When Charts Service is used, the range of Spreadsheet can be converted to an image blob.

    Sample script:

    function add_WSA(){
      //Opening the Spreadsheet
      var ss = SpreadsheetApp.openById("insertSpreadsheetID");
      var range = ss.getRange("example!A1:F20");//in A1 Notation
      //Conversion into an png image
    
    
      // I modified below script.
      const [header, ...values] = range.getDisplayValues();
      const table = Charts.newDataTable();
      header.forEach(e => table.addColumn(Charts.ColumnType.STRING, e));
      values.forEach(e => table.addRow(e));
      const image = Charts.newTableChart().setDataTable(table.build()).setDimensions(500, 500).setOption('alternatingRowStyle', false).build().getBlob();
    
    
      //Opening the specific Slide (Nr. 3)
      var slide = SlidesApp.openById("mySlidesID").getSlides()[2]; 
      
      //Insertion of image
      slide.insertImage(image);
    }
    

    Result:

    When above script is run, the following sample result can be obtained.

    enter image description here

    Note:

    • Please use this script with enabling V8.
    • In this case, for example, when you want to change the font color, please use HTML code in each cell value.

    Reference: